本文介绍了从HTTP响应中获取JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从Http get响应中获取 JSON 对象:
I want to get a JSON object from a Http get response:
这是我当前的代码Http get:
Here is my current code for the Http get:
protected String doInBackground(String... params) { HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(params[0]); HttpResponse response; String result = null; try { response = client.execute(request); HttpEntity entity = response.getEntity(); if (entity != null) { // A Simple JSON Response Read InputStream instream = entity.getContent(); result = convertStreamToString(instream); // now you have the string representation of the HTML request System.out.println("RESPONSE: " + result); instream.close(); if (response.getStatusLine().getStatusCode() == 200) { netState.setLogginDone(true); } } // Headers org.apache.http.Header[] headers = response.getAllHeaders(); for (int i = 0; i < headers.length; i++) { System.out.println(headers[i]); } } catch (ClientProtocolException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } return result; }这是convertSteamToString函数:
Here is the convertSteamToString function:
private static String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); }现在我只是得到一个字符串对象。如何获取JSON对象。
Right now I am just getting a string object. How can I get a JSON object back.
推荐答案您获得的字符串只是JSON Object.toString()。这意味着你得到了JSON对象,但是是一种String格式。
The string that you get is just the JSON Object.toString(). It means that you get the JSON object, but in a String format.
如果你应该得到一个JSON对象你可以放:
If you are supposed to get a JSON Object you can just put:
JSONObject myObject = new JSONObject(result);更多推荐
从HTTP响应中获取JSON对象
发布评论