猿问

如何在Java中将http响应正文作为字符串获取?

我知道以前有一种通过apache commons获取它的方法,如此处记录的:http : //hc.apache.org/httpclient-legacy/apidocs/org/apache/commons/httpclient/HttpMethod.html 和此处的示例:


http://www.kodejava.org/examples/416.html


但我认为这已被弃用。还有其他方法可以在Java中发出http get请求,并以字符串而不是流的形式获取响应正文吗?


PIPIONE
浏览 1263回答 3
3回答

精慕HU

这是我的工作项目中的两个示例。使用EntityUtils和HttpEntityHttpResponse response = httpClient.execute(new HttpGet(URL));HttpEntity entity = response.getEntity();String responseString = EntityUtils.toString(entity, "UTF-8");System.out.println(responseString);运用 BasicResponseHandlerHttpResponse response = httpClient.execute(new HttpGet(URL));String responseString = new BasicResponseHandler().handleResponse(response);System.out.println(responseString);

MYYA

这是我正在使用来自Apache的httpclient库的另一个简单项目的示例:String response = new String();List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);nameValuePairs.add(new BasicNameValuePair("j", request));HttpEntity requestEntity = new UrlEncodedFormEntity(nameValuePairs);HttpPost httpPost = new HttpPost(mURI);httpPost.setEntity(requestEntity);HttpResponse httpResponse = mHttpClient.execute(httpPost);HttpEntity responseEntity = httpResponse.getEntity();if(responseEntity!=null) {&nbsp; &nbsp; response = EntityUtils.toString(responseEntity);}只需使用EntityUtils即可将响应主体作为字符串获取。很简单。
随时随地看视频慕课网APP

相关分类

Java
我要回答