2015-11-03 47 views
2

我使用HttpURLConnection的get方法调用API的方法,解析HttpURLConnection的得到响应

请找我写的方法:

 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活动中显示该结果。

回答

1

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

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

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