Java 发送HTTP GET请求的最佳实践
发送HTTP GET请求是否有比以下更好的实践Java 发送HTTP GET请求的最佳实践,java,http-get,Java,Http Get,发送HTTP GET请求是否有比以下更好的实践 private StringBuffer getData(String url) throws Exception { URL obj; obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET");
private StringBuffer getData(String url) throws Exception
{
URL obj;
obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response;
}
我认为您应该做的两个简单更改是在
finally
块中关闭输入流,并使用StringBuilder
而不是StringBuffer
此外,如果收到错误响应(400+、500+等),您可能希望检查响应代码并引发异常
编辑:
如果您计划以任何方式缓冲所有内容,并且不介意使用库,那么您可以简单地执行以下操作:
Request.Get("http://some.url").execute().returnContent();
使用。为了清晰起见,您可能需要提到这是在使用Apache HttpComponents。此外,我认为使用finally块并调用
httpGet.releaseConnection()
来释放底层连接仍然是最佳做法。只要使用Request.Get(“http://some.urlexecute().returnContent()代码>非常酷!是的,apache组件正是我在实践中寻找的关于比较的东西。谢谢你的澄清!也许是Webclient.DownloadString?
String uri = "your url";
HttpParams httpParams = new BasicHttpParams();
HttpClient client = new DefaultHttpClient(httpParams);
HttpGet request = new HttpGet(uri);
HttpResponse response = client.execute(request);
String responseStr = buildResponseFromEntity(response.getEntity());
private String buildResponseFromEntity(HttpEntity entity)
throws IllegalStateException, IOException {
BufferedReader r = new BufferedReader(new InputStreamReader(
entity.getContent()));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
return total.toString();
}
// check if error
if (response.getStatusLine().getStatusCode() != 200) {
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(responseStr);
} catch (Exception e) {
// do your code
}
}