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
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 に答える