解析Httpurlconnection获得响应

时间:2015-11-03 04:24:54

标签: android parsing get httpurlconnection

我有一个使用Httpurlconnection get方法调用api的方法,

请找到我写的方法:

       private String sendGet(CallWebserviceActivity context) throws Exception {
       String url = "http://myurl/";
       URL obj = new URL(url);
       HttpURLConnection con = (HttpURLConnection)                               obj.openConnection();
       con.setRequestMethod("GET");
       con.setDoOutput(true);
       int responseCode = con.getResponseCode();
       System.out.println("\nSending 'Get' request to URL : " +    url+"--"+responseCode);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

       System.out.println("Response : -- " + response.toString());
       return response.toString();
    }

这里我得到一个格式为JSON Object的字符串作为结果。我希望能够将结果作为键的值,以便我可以在我的android活动中显示。

1 个答案:

答案 0 :(得分:3)

从字符串构建JSONObject。然后从密钥中获取值...

JSONObject jsonResponse = new JSONObject(response.toString());
String value = jsonResponse.getString("Key");

请注意,字符串应格式正确JSON。