3

发送 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;
}
4

2 回答 2

4

我认为您应该进行的两个简单更改是在一个finally块中关闭您的输入流,并使用 aStringBuilder而不是StringBuffer.

此外,如果您收到错误响应(400+、500+ 等),您可能需要检查响应代码并抛出异常。

编辑:

如果您打算缓冲所有内容,并且您不介意使用库,那么您可以简单地执行以下操作:

Request.Get("http://some.url").execute().returnContent();

使用Apache HttpComponents

于 2013-07-11T18:19:53.723 回答
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
            }
}
于 2013-07-11T18:38:49.627 回答