发送HTTP 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;
}
答案 0 :(得分:4)
我认为您应该做的两个简单更改是在finally
块中关闭输入流,并使用StringBuilder
代替StringBuffer
。
此外,如果收到错误响应(400 +,500 +等),您可能需要检查响应代码并抛出异常。
编辑:
如果您计划缓冲所有内容,并且不介意使用库,那么您可以这样做:
Request.Get("http://some.url").execute().returnContent();
答案 1 :(得分:4)
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
}
}