HTTP Responses - Android
I am trying to make my application post something to my webserver (located at IP 10.0.2.2) and receive the response. I'm using a HttpHelper object to do all the server-interaction methods. At the moment my response variable is not getting anything back. Through debugging I know that the loop:
while ((line = rd.readLine()) != null) {
is never entered, but it should be entered because it should receive the line 'OK' surely?
Thanks very much for your help!
The webpage code is just:
header("HTTP/1.1 200 OK");
The java code is:
List<NameValuePair> data = new ArrayList<NameValuePair>();
HttpHelper httpHelper = new HttpHelper("http://10.0.2.2/", data);
StringBuilder response = httpHelper.postData();
...
public class HttpHelper {
final HttpClient client;
final HttpPost post;
final List<NameValuePair> data;
public HttpHelper(String address, List<NameValuePair> data) {
client = new DefaultHttpClient();
post = new HttpPost(address);
this.data = data;
}
private class GetResponseTask extends AsyncTask<Void, Void, StringBuilder> {
protected StringBuilder doInBackground(Void... arg0) {
try {
HttpResponse response = client.execute(post);
return inputStreamToString(response.getEntity().getContent());
} catch (ClientProtocolException e) {
开发者_如何学Python Log.e("debug", e.getLocalizedMessage());
} catch (IOException e) {
Log.e("debug", e.getLocalizedMessage());
}
return null;
}
}
public StringBuilder postData() {
try {
post.setEntity(new UrlEncodedFormEntity(data));
return (new GetResponseTask().execute()).get();
} catch (UnsupportedEncodingException e) {
Log.e("debug", e.getLocalizedMessage());
} catch (InterruptedException e) {
Log.e("debug", e.getLocalizedMessage());
} catch (ExecutionException e) {
Log.e("debug", e.getLocalizedMessage());
}
return null;
}
private StringBuilder inputStreamToString(InputStream is)
throws IOException {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
while ((line = rd.readLine()) != null) {
Log.v("debug", "top of readlineloop");
total.append(line);
Log.v("debug-readline", line);
}
// Return full string
return total;
}
}
The response entity, the one returned by getEntity(), does not include the response headers, and it looks like that's what you're interested in. To retrieve the status code, use:
response.getStatusLine().getStatusCode()
The "entity" is reponse content.
EDIT: to emit content from PHP, use echo
, print_r()
, var_dump()
, numerous other functions, and - most importantly - all text outside of <?php...?>
tags.
精彩评论