解析Httpurlconnection获取响应 [英] Parsing the Httpurlconnection get response
本文介绍了解析Httpurlconnection获取响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个使用Httpurlconnection get方法调用api的方法,
请找到我写的方法:
private String sendGet(CallWebserviceActivity context)抛出Exception {
String url =http:// myurl /;
URL obj =新的URL(url);
HttpURLConnection con =(HttpURLConnection)obj.openConnection();
con.setRequestMethod(GET);
con.setDoOutput(true);
int responseCode = con.getResponseCode();
System.out.println(\\\
Sending'Get'request to URL:+ url + - + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer(); ((inputLine = in.readLine())!= null){
response.append(inputLine);
}
in.close();
System.out.println(Response: - + response.toString());
return response.toString();
$ b $ p
$ b 这里我得到了一个格式为JSON Object的字符串作为结果。希望能够将结果作为关键字的值,以便我可以在我的android活动中显示该结果。
解决方案从字符串构建JSONObject。然后从键中获取值...
JSONObject jsonResponse = new JSONObject(response.toString());
字符串值= jsonResponse.getString(Key);
请注意,字符串应该采用正确的JSON格式。
I have a method calling an api using Httpurlconnection get method,
Please find the method i have written:
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();
}
Here i am getting a string of the format JSON Object as a result.I want to able to take result as value of the key so that i can show that in my android activity.
解决方案 Build a JSONObject from string. Then get the value from key ...
JSONObject jsonResponse = new JSONObject(response.toString());
String value = jsonResponse.getString("Key");
Note that string should be properly formatted JSON.
这篇关于解析Httpurlconnection获取响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文