Test an outgoing HTTP request in Spring - java

I feel very sorry to ask that question because I am pretty sure that this was already asked. But by searching here or with google I always land at sites where REST services with incoming requests are tested.
In my case I have a method that sends a request to a server. I want to test if that request is correct. I use java and spring boot. Every time I test that, the request is send to the server. Can I intercept that?
public void buy(double price) {
final String timestamp = String.valueOf(System.currentTimeMillis());
final String amount = String.valueOf(observer.requestedAmount);
final String ressouce = GetValuesTypes.getRessource("user").get(observer.getRelatedUser);
String queryArgs = "wwww.doSomething.com/" + ressouce;
String hmac512 = HMAC512.hmac512Digest(queryArgs);
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(GetValuesTypes.getURL());
post.addHeader("Key", GetValuesTypes.getKey());
post.addHeader("Sign", hmac512);
try {
post.setEntity(new ByteArrayEntity(queryArgs.getBytes("UTF-8")));
} catch (UnsupportedEncodingException e) {
System.out.println("Exception in run");
}
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("command", "order"));
params.add(new BasicNameValuePair("ressource", ressource));
params.add(new BasicNameValuePair("rate", String.valueOf(rate)));
params.add(new BasicNameValuePair("amount", amount));
params.add(new BasicNameValuePair("timestamp", timestamp));
try {
post.setEntity(new UrlEncodedFormEntity(params));
CloseableHttpResponse response = httpClient.execute(post);
HttpEntity entity = response.getEntity();
Scanner in = new Scanner(entity.getContent());
String orderNumber = "";
while (in.hasNext()) {
orderNumber = in.nextLine();
}
String[] findOrderNumber = orderNumber.split(".");
long lastOrderNumber = -1;
try {
lastOrderNumber = Long.valueOf(findOrderNumber[3]);
} catch (NumberFormatException exception) {
System.out.println("NumberFormatException");
} finally {
if (lastOrderNumber != -1) {
observer.setOrderNumber(lastOrderNumber);
}
}
in.close();
EntityUtils.consume(entity);
httpClient.close();
} catch (IOException e) {
System.out.println("Exception occured during process");
}
}
I would appreciate your help very much.

This is a typical question that are faced by all the people who are trying to write tests for their code (and this also means that there are many articles on the net about how to do it).
In this particular case, I see two ways:
if you want to write a unit test: instead of creating HttpClient, you should make it configurable, to be able to substitute it by mock in the unit tests. You can hold it as a class member or provide as a second argument to buy() method. Later, in a unit test, you need to provide a fake version of HttpClient (mock) that allows you to inspect its arguments to ensure that they're equal to expected.
if you want to write an integration test: you need to run a fake service that behaves like a real server but also allows to inspect received requests. In an integration test, you need to configure HttpClient to connect to this fake server and after that check that the server received request from a client.
How to implement this, is up to you and technologies with that you're familiar to.

Related

Connecting to backend server from app via HTTPS cause delays/timeouts

I'm developing an android app which connects to backend server via HTTPS. Everything is working properly when I use mobile data - no errors and other similar things. However, when I turn on WiFi and try to get some data from backend server I'm getting large delays (even 40 seconds) although I download just two lines of text, for example. I've also noticed that if I connect to backend server via HTTP, there is no problem using both mobile data and WiFi. I have tested many times if I set up SSL protocol properly and everything seems to be done properly.
I'm providing to you a piece of code, which is responsible for connecting with backend server from the app:
private boolean downloadData() {
try {
URI uri = new URI("https://www.example.com/resources/script/get_data.php");
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(uri);
httpPost.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
httpPost.setHeader("Pragma", "no-cache");
HttpResponse httpResponse = httpClient.execute(httpPost);
String result = EntityUtils.toString(httpResponse.getEntity());
if(result.equals("error")) {
return false;
}
result = result.replaceAll("\"", "\\\"");
JSONArray jsonArray = new JSONArray(result);
// code which receive and parse data from JSON
return true;
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
If you want to get some more information/pieces of code, write in comments.
Thanks for your help
You need to trace you requests by some monitoring program. After that you can see what node creates a delay. And pls show this data.

Android connectivity with MySql using jsp

I am developing a web app in JSP. For same project I'm developing an Android app. The web app uses Apache Tomcat and MySQL. Now I want to make registration form and login form of the Android application that interface with same MySQL database. But how?
I did find many tutorials but all are using PHP scripts. I'm using Eclipse for web development and Android Studio for android app.
This will involve at least 4 steps
Create a POJO that will represent your data.
public class LoginData implements Serializable{
public String loginName;
public String loginPassword;
//all other attributes that you need to send over HTTP
}
Create s simple HTTP client (either using Java API, Apache HTTP client or some other library). My example is using Apache
//you only need 1 client so make it static
public static DefaultHttpClient getHttpClient(int timeout) {
DefaultHttpClient client = null;
SchemeRegistry Current_Scheme = new SchemeRegistry();
Current_Scheme.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
HttpParams Current_Params = new BasicHttpParams();
//set initial params
HttpConnectionParams.setConnectionTimeout(Current_Params, timeout);
HttpConnectionParams.setSoTimeout(Current_Params, timeout);
ThreadSafeClientConnManager Current_Manager = new ThreadSafeClientConnManager(Current_Params, Current_Scheme);
client = new DefaultHttpClient(Current_Manager, Current_Params);
return client;
}
In order to send your POJO, you should first serialize it (the first argument is Object so that it can accept any type, not just LoginData)
//The data will be formatted as application/x-www-form in this way (BTW, web apps use this by default)
HttpEntity serializePOJO(Object o,String encoding)
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
Map<String, Object> maps=objectMapper.convertValue(o, Map.class);
Set<String> keys=maps.keySet();
Iterator<String> itr=keys.iterator();
while(itr.hasNext()){
String key=itr.next();
Object value=maps.get(key);
if(value!=null){
postParams.add(new BasicNameValuePair(key, value.toString()));
}
}
UrlEncodedFormEntity data=null;
try {
data = new UrlEncodedFormEntity(postParams,encoding);//e.g.UTF-8
} catch (UnsupportedEncodingException e) {
throw e;
}
return data;
}
Issue a HTTP request
public void checkLogin(LoginData data)throws Exception
{
String url = "localhost:8080/myApp/login";
HttpPost request=null;
try{
request=new HttpPost(url);
request.setEntity(serializePOJO(data));
HttpResponse response=getHttpClient(10000).execute(hg);
if(response.getStatusLine().getStatusCode()!=200){
//handle exception
}
}finally{
if(request!=null){
request.releaseConnection();
}
}
}
You can initialize objectMapper as
objectMapper=new ObjectMapper();
objectMapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Your servlet should connect to the database and do all the processing , not the JSP page.

How to switch from HttpClient to HttpUrlConnection?

I am creating an Android application and I send data from Android application to servlet through HttpClient. I use HttpPost method.
I read in Android developer site that Apache HttpClient library has some bug in Android Froyo 2.2 and after all it's good practice to use HttpUrlConnection instead HttpPost. So I want to convert my HttpPost code to HttpUrlConnectio but don't know how.
I am posting my Android code as well as servlet code here
Android code
private String postData(String valueIWantToSend[])
{
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try
{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("param1",valueIWantToSend[0]));
nameValuePairs.add(new BasicNameValuePair("param2", valueIWantToSend[1]));
nameValuePairs.add(new BasicNameValuePair("param3", valueIWantToSend[2]));
nameValuePairs.add(new BasicNameValuePair("param4", valueIWantToSend[3]));
nameValuePairs.add(new BasicNameValuePair("param5", valueIWantToSend[4]));
nameValuePairs.add(new BasicNameValuePair("param6", valueIWantToSend[5]));
nameValuePairs.add(new BasicNameValuePair("param7", valueIWantToSend[6]));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
/* execute */
HttpResponse response = httpclient.execute(httppost);
HttpEntity rp = response.getEntity();
//origresponseText=readContent(response);
}
catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
}
catch (IOException e)
{
// TODO Auto-generated catch block
}
return null;
}
and here is my servlet code
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
ObjectOutputStream out = new ObjectOutputStream(response.getOutputStream());
Enumeration paramNames = request.getParameterNames();
String params[] = new String[7];
int i=0;
while(paramNames.hasMoreElements())
{
String paramName = (String) paramNames.nextElement();
System.out.println(paramName);
String[] paramValues = request.getParameterValues(paramName);
params[i] = paramValues[0];
System.out.println(params[i]);
i++;
}
}
When I read the already mentioned Google post about best practices doing HTTP requests in newer versions of Android, I thought somebody was kidding me. HttpURLConnection is really a nightmare to use, compared to almost any other way to communicate with HTTP servers (apart from direct Socket communication).
I didn't find a really slim library for Android to do the heavy lifting, so I wrote my own. You can find it at DavidWebb including a list of alternative libraries which I found (unfortunately) after developing the library.
Your code would look more or less like this:
public void testPostToUrl() throws Exception {
String[] values = new String[3];
Webb webb = Webb.create();
Response<String> response = webb
.post("http://www.example.com/abc.php")
.param("param1", values[0])
.param("param2", values[1])
.param("param3", values[2])
.asString();
assertEquals(200, response.getStatusCode());
assertNotNull(response.getBody());
assertTrue(response.getBody().contains("my expected result"));
}
public void testPostToUrlShorter() throws Exception {
String[] values = new String[3];
Webb webb = Webb.create();
String result = webb
.post("http://www.example.com/abc.php")
.param("param1", values[0])
.param("param2", values[1])
.param("param3", values[2])
.ensureSuccess()
.asString()
.getBody();
assertTrue(result.contains("my expected result"));
}
You should absolutely be using HttpUrlConnection:
For Gingerbread and better, HttpURLConnection is the best choice... New applications should use HttpURLConnection...
--Google (circa. 2011)
However, there is no easy way just to "switch". The APIs are totally different. You are going to have to rewrite your networking code. There are perfect examples in the documentation on how to submit a GET and POST requests as well as in the SDK sample apps.
You don't have to switch, you can continue using apache's library like I described in this answer. There are really no downsides to continue using apache's library - it's only google's marketing.

Authentication error: Unable to respond to any of these challenges: {} Android - 401 Unauthorized

Authentication error: Unable to respond to any of these challenges: {} Android - 401 Unauthorized
I have taken reference from this link
Authentication Error when using HttpPost with DefaultHttpClient on Android
I am working on android app in that backed in Drupal. In that I am sending data from android app to drupal website - webservice in JSON format. Now I can read JSON data from Drupal webservice and writing it in my android application. But facing problem in writing on drupal from android, it generates response with status code
401 Unauthorized
From android native app it generates 401 , while from phonegap-from android when I initiate AJAX request it works perfectly & writes an article or page on drupal website. so that means webservice work perfectly &
my phonegap android app works perfectly there is problem with Android native JAVA application
I am running my android application on Android2.3.4 -> Samsung Galaxy
S Plus - Samsung GT-I9001
here is my code for java android.
==============================
String url = "XXX";
strResponse1 = makeWebForPostIdea(url,title,body);
public static String makeWebForPostIdea(String url, String title,String body)
{
JSONStringer jsonobject = null;
JSONObject json = null;
JSONObject jsonnode = null;
DefaultHttpClient client = new DefaultHttpClient();
Credentials creds = new UsernamePasswordCredentials("username", "password");
client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), creds);
HttpPost post = new HttpPost(url);
System.out.println("value of the post =============> "+post);
try {
JSONObject jsonvalue = new JSONObject();
jsonvalue.put("value", body.toString());
JSONArray array = new JSONArray();
array.put(jsonvalue);
jsonnode = new JSONObject();
jsonnode.put("und", array);
System.out.println("######2 jsonnode=======>"+jsonnode.toString());
} catch (JSONException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
try {
jsonobject = new JSONStringer().array().object().key("und").object().key("0").object().key("value").value(body).endObject().endObject().endObject().endArray();
System.out.println("=============>"+jsonobject);
} catch (JSONException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("type","page"));
params.add(new BasicNameValuePair("title",title));
params.add(new BasicNameValuePair("language","und"));
params.add(new BasicNameValuePair("body",jsonobject.toString()));
System.out.println("value of the params =============> "+params);
UrlEncodedFormEntity formEntity = null;
try {
formEntity = new UrlEncodedFormEntity(params);
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
post.setEntity(formEntity);
try {
HttpResponse response = client.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("=========> statusCode post idea=====> "+statusCode);
if (statusCode == HttpStatus.SC_OK)
{
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
return iStream_to_String(is);
}
else
{
return "Hello This is status ==> :"+String.valueOf(statusCode);
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static String iStream_to_String(InputStream is1) {
BufferedReader rd = new BufferedReader(new InputStreamReader(is1), 4096);
String line;
StringBuilder sb = new StringBuilder();
try {
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String contentOfMyInputStream = sb.toString();
return contentOfMyInputStream;
}
}
}
here is the logcat that I am getting.
08-09 12:41:29.063: I/System.out(336): value of the post =============> org.apache.http.client.methods.HttpPost#4053c3c8
08-09 12:41:29.093: I/System.out(336): ######2 jsonnode=======>{"und": [{"value":"ddddddd"}]}
08-09 12:41:29.093: I/System.out(336): =============>[{"und":{"0":{"value":"ddddddd"}}}]
08-09 12:41:29.103: I/System.out(336): value of the params =============> [type=page, title=hhhh, language=und, body=[{"und":{"0":{"value":"ddddddd"}}}]]
08-09 12:41:30.913: W/DefaultRequestDirector(336): Authentication error: Unable to respond to any of these challenges: {}
08-09 12:41:30.913: I/System.out(336): =========> statusCode post idea=====> 401
08-09 12:41:30.924: I/System.out(336): =========> Response from post idea => Hello This is status ==> :401
Here is my PhoneGap Ajax request it works perfectly.
$('#page_node_create_submit').live('click',function(){
var title = $('#page_node_title').val();
//if (!title) { alert('Please enter a title.'); return false; }
var body = $('#page_node_body').val();
//if (!body) { alert('Please enter a body.'); return false; }
// BEGIN: drupal services node create login (warning: don't use https if you don't have ssl setup)
$.ajax({
url: "XXX",
type: 'post',
data: 'node[type]=page&node[title]=' + encodeURIComponent(title) + '&node[language]=und&node[body][und][0][value]=' + encodeURIComponent(body),
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('page_node_create_submit - failed to login');
console.log(JSON.stringify(XMLHttpRequest));
console.log(JSON.stringify(textStatus));
console.log(JSON.stringify(errorThrown));
},
success: function (data) {
$.mobile.changePage("index.html", "slideup");
}
});
// END: drupal services node create
return false;
});
=================================================================================
Edit :
I have tried various methods for Apache httpclient for my error.During this time I have done some research and searched on google and found out some interesting stuff.
1st thing that I found it that Android-Google Officially does not recommend Apache HttpClient that I am using in my code. Check this link. In that Link message from Jesse Wilson from the Dalvik team. In that they suggest to use HttpURLConnection instead of DefaultHttpClient and also written that Android team will no longer develop Apache httpclient . so its the older version that I am using.
http://android-developers.blogspot.in/2011/09/androids-http-clients.html
2nd thing that I have found form this link. It suggests that Android is shipping with Apache's HttpClient 4.0 Beta2, which has a pitfall, when it comes to Basic Authentication. The Authentication method that I am using is of HttpClient 3.x , that I have found out from this link.
check the link.
http://hc.apache.org/httpclient-3.x/authentication.html#Preemptive_Authentication
So the version issue.
http://dlinsin.blogspot.in/2009/08/http-basic-authentication-with-android.html
I have also found some links with potential solution of this problem.
http://ogrelab.ikratko.com/using-newer-version-of-httpclient-like-4-1-x/
Apache HttpClient 4.1 on Android
What version of Apache HTTP Client is bundled in Android 1.6?
From these links , I made a conclusion that if we upgrade the Apache HttpClient to latest stable version , then this problem can be solved.
But this is directly no possible , as Android Team has officially stopped the support for the Apache httpclient.
With this link It could be possible to solve. I have not tried it but I am working on it.
It is the library that can help in upgrading httpclient version in Android.
http://code.google.com/p/httpclientandroidlib/
The other solution could be using HttpURLConnection .I am also working on it.
But most people here on stackoverflow and Internet seems to using DefaultHttpCLient with Android. And ofcourse it is also working with me throughout my application including login,registration,reading from server and session and other functionality.Just it is not working with directly post some article to my server-Drupal website.
It works perfectly with POST request during registration of user on server.
So friends , any suggestions regarding this ? why it is not working just with posting article ?
How come it works from the PhoneGap but not Java. PhoneGap runs the app in a web container and so already has been authenticated - and you have all the right cookies. AJAX will share the same session that and everything 'just works'.
However HTTPClient is a completely different - you are initiating a brand new HTTP session and everything has to be right.
A few comments on how HTTP Auth works:
There are several HTTP authentication methods - and it's the web server that chooses which. Before going any further, check your Drupal configuration to work out whether it is:
Basic Auth (username and password). Everyone and their dog supports this, but it's very insecure. See http://en.wikipedia.org/wiki/Basic_access_authentication for more details
Digest (username and challenge/response hash with MD5. This is more secure but much more complex. Note that MD5 is generally considered weak now. Many libraries support it, including Apache. See http://en.wikipedia.org/wiki/Digest_access_authentication for more details
NTLM (a variant of Kerberos/SPEGNO) which is implemented on IIS. This is not generally supported from Java, although HTTPClient does profess to - but using a different Credentials object. See http://hc.apache.org/httpclient-3.x/authentication.html#NTLM
(Note also that the web container has the 'smarts' to be able to try different authentication methods as requested by the server, all behind the scenes)
Also check the Drupal web logs. A few pointers:
Did you see the HTTPClient connect at all. And is the URL going to the correct resource. Always worth checking from the server's perspective...
Did it go to the right server? One example of what could go wrong: Are you using IP
addresses in the URL against a multi-homed web server, so the request goes to the wrong server?
Check that the authentication sent by the client pre-emptively is the correct type (basic, digest, NTLM)
Let me know if this helps. If not, and you can give more details as per this post, I can follow up with more advice.
You might try to check: How to do http post using apache httpclient with web authentication?
It uses a HttpInterceptor to inject the authentication data, when required
I'd suggest to test first the PHP side out the app. There are several ways to make your own calls including headers and auth. From curl to GraphicalHttpClient (http://itunes.apple.com/us/app/graphicalhttpclient/id433095876?mt=12 , I personally use that and it works decently). There some other options like REST client debugger (https://addons.mozilla.org/en-US/firefox/addon/restclient/)
This way you'll be able to test your call in so many ways which is pain doing directly in the client (sometimes it's just changing from http to https or adding the type of your token in the Authorization header and that's much easier to be madeo n the fly).
Once everything works as expected, reproduce the same call, headers and body in your client and you are ready to go.
I was running into the same "DefaultRequestDirector: Authentication error: Unable to respond to any of these challenges: {}" problem with Drupal services using the loopj android-async-http library (highly recommend it).
The key to the solution for me was in Jose L Ugia's comment in one of the answers regarding paying special attention to the JSON output from Drupal. I was trying to catch a JSONObject but the real message was in array format "["Wrong username or password."]". Switching to JSONArray caught the error properly and allowed me to handle it. In your case I believe it is because you are not posting the login credentials as drupal services expects it.
You should remember with Drupal Services you should do system/connect and grab the session, followed by user/login (and the user/password passed in as parameters) and grab the session and then all your subsequent requests should work. This is why I like using the loopj library because it makes all these requests more manageable. Here is a very basic example of connecting to drupal with loopj. All subsequent posts are easily done using the params.
public class Loopj {
private static final String TAG = "loopj";
private static AsyncHttpClient client = new AsyncHttpClient();
private final PersistentCookieStore myCookieStore;
public Loopj(Context context) {
myCookieStore = new PersistentCookieStore(context);
client.setCookieStore(myCookieStore);
client.addHeader("Content-type", "application/json");
}
public void systemConnect(String uri) throws JSONException {
client.post(uri + "/endpoint/system/connect", new JsonHttpResponseHandler() {
#Override
public void onSuccess(JSONObject json) {
Log.i("TAG", "Connect success =" + json.toString());
}
#Override
public void onFailure(Throwable e, String response) {
Log.e("TAG", "Connect failure");
}
});
}
public void userLogin(String uri) throws JSONException {
RequestParams params = new RequestParams();
params.put("username", username);
params.put("password", password);
client.post(uri + "/endpoint/user/login", params, new JsonHttpResponseHandler() {
#Override
public void onSuccess(JSONArray response) {
Log.i("TAG", "Login success =" + response.toString());
}
#Override
public void onFailure(Throwable e, JSONArray json) {
Log.e("TAG", "Login failure");
}
});
}

Open WebView with result from Http post

I having an issue from my HTTP Post.
The code I'm using are working (have tested to post data to a guestbook form and it worked).
Now what I want. I have created two EditText forms, that holds values. I have a submit button there I post this data (like the test I wrote about before), but now I want to post it into a login.php page (that in a normal browser redirects me to the member.php page).
Although I know the forms are correctly filled in and it successfully posted on the "test" site, I wanna get the response from login.php and check if the user is successfully logged in or if it failed, if succeeded -> redirect me to member.php page.
All I know is this:
HttpResponse response = httpclient.execute(httppost);
that executes the command. But how should I achieve the login check? Any further use of the response variable?
Well... your approach is not good at all. If you are going to allow user authenticate through your app, why do you want to redirect the user to a member.php page? why don't you just put the login form in a login.php file on the server and make the user browse through your site?
As user, if an app allows me to authenticate using EditTexts inside UI, I would expect to access all the content through the app instead of being redirected to a web interface.
Anyway, if you decide to continue doing it that way keep in mind that you would have to parse and process cookies manually, and inject them into the WebView (Google about the CookieManager class). That's the way how the user will really be logged-in in your web app.
Can you provide a small example of how to set it up? The stream I will get, is that a special server response for example, a successfully login?
Here you have:
public String getPostRequest(String url, String user, String pass) {
HttpClient postClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse response;
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("user", user));
nameValuePairs.add(new BasicNameValuePair("pass", pass));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = postClient.execute(httpPost);
if(response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
instream.close();
return result; // here is a string of the result!!!
}
}
} catch (Exception e) {}
return null; // if it gets here, something wrong happens with the connection
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
How do you use it? Something like this:
String result = getPostRequest("http://yourpage.com/login.php", "the username", "his/her pass");
if( result.equals("OK") ){
// voila!
}
I'm here supposing that you have something like this in your PHP code:
<?php
// login logic here
if( $success ){
die("OK");
}
?>

Categories