解析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对象格式的字符串。我希望能够将结果作为键的值,以便可以在我的android活动中显示出来。

Varun Verma

从字符串构建JSONObject。然后从键获取值...

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章