2015-11-03 39 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。