我知道曾经有一种方法可以在Apache Commons中获得它,如下所示:
http://hc.apache.org/httpclient-legacy/apidocs/org/apache/commons/httpclient/HttpMethod.html
...and这里有一个例子:
http://www.kodejava.org/examples/416.html
...but我认为这是被弃用的。
有没有其他方法可以在Java中发出http get请求,并以字符串而不是流的形式获取响应体?
发布于 2011-04-24 17:33:49
我能想到的每个库都会返回一个流。您可以在一个方法调用中使用Apache Commons IO中的IOUtils.toString()将InputStream读取到String中。例如:
URL url = new URL("http://www.example.com/");
URLConnection con = url.openConnection();
InputStream in = con.getInputStream();
String encoding = con.getContentEncoding();
encoding = encoding == null ? "UTF-8" : encoding;
String body = IOUtils.toString(in, encoding);
System.out.println(body);更新:我更改了上面的示例,以便使用响应中的内容编码。否则,它将默认使用UTF-8作为最佳猜测,而不是使用本地系统默认值。
发布于 2012-12-06 19:08:22
以下是我的工作项目中的两个示例。
使用EntityUtils和HttpEntity的
HttpResponse响应=httpClient.execute(新的HttpGet(URL));HttpEntity entity = response.getEntity();String responseString = EntityUtils.toString(entity,"UTF-8");HttpEntity BasicResponseHandler
HttpResponse response =httpClient.execute(新的HttpGet地址);String responseString =新的URL
发布于 2012-03-07 05:37:27
下面是我使用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) {
response = EntityUtils.toString(responseEntity);
}只需使用EntityUtils获取字符串形式的响应体即可。非常简单。
https://stackoverflow.com/questions/5769717
复制相似问题