0

我正在为 Android 使用http://hc.apache.org/httpcomponents-core-ga/httpcore/examples/org/apache/http/examples/ElementalHttpServer.java

我使用以下代码设置响应:

HttpResponse getResponse = new BasicHttpResponse(HttpVersion.HTTP_1_1, 404, "Not Found");
getResponse.setEntity(new StringEntity(new String("The requested resource " + target + " could not be found due to mismatch!!")));  
conn.sendResponseHeader(getResponse);
conn.sendResponseEntity(getResponse);

我在 Mozilla Poster 或浏览器中的响应具有标头 404 和响应正文:

The requested resource  could not be found due to mismatch!!HTTP/1.1 200 OK

如何仅获取 HTTP 正文字符串?为什么我得到 HTTP/1.1 200 OK 作为响应。我没有在我的代码中设置它。任何帮助表示赞赏。

在此处输入图像描述

4

3 回答 3

0

使用ResponseHandler. 一行代码。有关使用它的示例 Android 项目,请参见此处此处

public void postData() {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://www.yoursite.com/user");

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("id", "12345"));
        nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        ResponseHandler<String> responseHandler=new BasicResponseHandler();
        String responseBody = httpclient.execute(httppost, responseHandler);
        JSONObject response=new JSONObject(responseBody);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
} 

在 - http://www.androidsnippets.org/snippets/36/添加这篇文章和完整的 HttpClient 的组合

于 2013-01-15T13:12:03.367 回答
0

这可能会帮助你......我认为这response 是你需要的

HttpClient client = new DefaultHttpClient();

        HttpResponse httpResponse;

        try {
            httpResponse = client.execute(request);
            responseCode = httpResponse.getStatusLine().getStatusCode();
            message = httpResponse.getStatusLine().getReasonPhrase();

            HttpEntity entity = httpResponse.getEntity();

            if (entity != null) {

                InputStream instream = entity.getContent();
                response = convertStreamToString(instream);

                // Closing the input stream will trigger connection release
                instream.close();
            }

        } catch (ClientProtocolException e) {
            client.getConnectionManager().shutdown();
            e.printStackTrace();
        } catch (IOException e) {
            client.getConnectionManager().shutdown();
            e.printStackTrace();
        }
于 2013-01-15T13:25:54.823 回答
0

我定义的 handle() 方法有问题。我为每个请求创建一个新的 HttpResponse 而不是使用传入的响应

public void handle(HttpRequest request, HttpResponse response, HttpContext context)
于 2013-01-18T09:03:23.507 回答