Android And PHP Creating An API
I'm trying to set up a PHP API for my Android application to interact with, my problem is that the post data never seems to get posted and I can never retrieve the response body (H
Solution 1:
public String getResponse(String url, List<NameValuePair> nameValuePairs) {
url = url.replaceAll(" ", "%20");
String result = "ERROR";
Log.d("Pair", nameValuePairs.toString());
HttpClient httpclient = new DefaultHttpClient();
HttpParams http_params = httpclient.getParams();
http_params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
HttpConnectionParams.setConnectionTimeout(http_params, TIMEOUT);
HttpConnectionParams.setSoTimeout(http_params, TIMEOUT);
HttpResponse response = null;
try {
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
e.printStackTrace();
result = "ERROR";
} catch (IOException e) {
e.printStackTrace();
result = "ERROR";
}
try {
// Get hold of the response entity
HttpEntity entity = null;
if (response != null) {
entity = response.getEntity();
}
if (entity != null) {
InputStream inputStream = entity.getContent();
result = convertStreamToString(inputStream);
}
} catch (IOException e) {
result = "ERROR";
}
httpclient.getConnectionManager().shutdown();
return result;
}
Use this Method with AsyncTask or background thread
Solution 2:
This one is working for me. Please do take care of exceptions ans error handling. Key121 variable is your php file url.
class callServiceTask extends AsyncTask<Void, Void, Void>
{
@Override
protected Void doInBackground(Void... params) {
loginCheck();
return null;
}
}
public void loginCheck()
{
InputStream is = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("aa","11"));
nameValuePairs.add(new BasicNameValuePair("bb","22"));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(KEY_121);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e)
{
Log.e("log_tag", "Error:"+e.toString());
}
//convert response to string
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();
result=sb.toString();
Log.e("log_tag", "----------------"+result);
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
}
You need to use stream and buffered reader for analysing response. Do check and let us know.
Post a Comment for "Android And PHP Creating An API"