HTTP响应 - Android

时间:2011-09-02 15:35:58

标签: android http-headers httpresponse

我正在尝试将我的应用程序发布到我的网络服务器(位于IP 10.0.2.2)并收到响应。我正在使用HttpHelper对象来执行所有服务器交互方法。目前我的响应变量没有得到任何回报。通过调试我知道循环:

while ((line = rd.readLine()) != null) {

永远不会输入,但是应该输入它,因为它 肯定会收到'OK'这一行?

非常感谢你的帮助!

网页代码只是:

header("HTTP/1.1 200 OK");

java代码是:

        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) {
            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;
}
}

1 个答案:

答案 0 :(得分:2)

响应实体(由getEntity()返回的实体不包含响应标头,看起来就像你感兴趣的那样。要检索状态代码,请使用:

response.getStatusLine().getStatusCode()

“实体”是响应内容。

编辑:要从PHP发出内容,请使用echoprint_r()var_dump(),众多其他功能,以及 - 最重要的 - <?php...?>标记之外的所有文字。