Pages

Friday 26 July 2013

Cosume PHP(GET METHOD) webservice in android.

Here i am going to show you the exact code for cosume php webservice in android. But in this example i have passes emailid and password in the url to check whether the user is valid or not.
To consume php get method we will use HttpGet.

Get the response InputStream like this:

InputStream is = null;

HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

Full Code:

  InputStream is = null;
JSONObject jObj = null;
String json = "";

       //Place your own url here
String URL = "http://domain.com/login.php?email="
+ username.getText().toString().trim().toLowerCase()
+ "&password="
+ password.getText().toString().trim().toLowerCase() + "";

   Log.d("username", username.getText().toString().trim()
   .toLowerCase());
   Log.d("password", password.getText().toString().trim()
   .toLowerCase());

   // Making HTTP request
   // (http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/)

   try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);

Log.d("pre", URL);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

   } catch (UnsupportedEncodingException e) {
e.printStackTrace();
   } catch (ClientProtocolException e) {
e.printStackTrace();
   } catch (IOException e) {
e.printStackTrace();
   }

   try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
   sb.append(line + "n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
   } catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
   }

   // try parse the string to a JSON object
   try {
jObj = new JSONObject(json);
   } catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
   }

   // return JSON String

   Log.d("test", jObj.toString());


Manifest.xml:

Add the following line in your manifest.
<uses-permission android:name="android.permission.INTERNET"/>

convert httpresponse to string android 

No comments:

Post a Comment