我正在使用http://hc.apache.org/httpcomponents-core-ga/httpcore/examples/org/apache/http/examples/ElementalHttpServer.java for Android。
我使用以下代码设置响应:
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作为回应。我不在我的代码中设置它。任何帮助表示赞赏。
答案 0 :(得分:0)
使用ResponseHandler
。一行代码。有关使用它的示例Android项目,请参阅here和here。
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
}
}
添加此帖子和完整HttpClient的组合
答案 1 :(得分: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();
}
答案 2 :(得分:0)
我定义的handle()方法存在问题。我正在为每个请求创建一个新的HttpResponse,而不是使用
中传递的响应public void handle(HttpRequest request, HttpResponse response, HttpContext context)