Android HTTP Get和结果字符串

时间:2012-09-29 00:03:01

标签: android http-get

我是开发的android方面的新手,我知道我想尝试的一件事是如何使用HTTP Get。我已经完成了整个方法设置,以便发送文本并将结果以字符串形式返回,但我想知道的是如何获取该字符串并提取我真正需要的部分。例如,字符串以

返回
{"id":"124343","name":"somename" }

如果我只是想获得启动的id部分,我将如何在android中执行此操作。我正在搜索文档,但到目前为止我还没有找到任何东西,然后我发现的大部分内容都围绕着使用JSON。

下面是我正在使用的代码(我已经从几个不同的帖子一起编译)但是我可能需要切换到使用JSON进行解析,我只是不确定在哪里进行更改

     //This class is called after a button is pressed and the HTTPGet string is compiled from text within a textview and a static string (this already works)
     private class LongRunningGetIO extends AsyncTask<Void, Void, String> {
    protected String getASCIIContentFromEntity(HttpEntity entity)
            throws IllegalStateException, IOException {
        InputStream in = entity.getContent();
        StringBuffer out = new StringBuffer();
        int n = 1;
        while (n > 0) {
            byte[] b = new byte[4096];
            n = in.read(b);
            if (n > 0)
                out.append(new String(b, 0, n));
        }
        return out.toString();
    }

    @Override
    protected String doInBackground(Void... params) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        String question = questionText.getText().toString();
        String newString = httpPath + "?userText=" + question;
        Log.i("Message", newString);
        HttpGet httpGet = new HttpGet(newString);
        String text = null;
        try {
            HttpResponse response = httpClient.execute(httpGet,
                    localContext);
            HttpEntity entity = response.getEntity();
            text = getASCIIContentFromEntity(entity);


        } catch (Exception e) {
            return e.getLocalizedMessage();
        }
        return text;
    }


    protected void onPostExecute(String results) {
        if (results != null) {
            Log.i("String", results);
        }
    }
}

2 个答案:

答案 0 :(得分:2)

这是从JSON字符串

中提取数据的方法
JSONObject obj =  new JSONObject(YourJSONString);
String id = obj.getString("id");
String name = obj.getString("name");

答案 1 :(得分:1)

这是你想要的::

HttpGet httpGet = new HttpGet(newString);
String text = null;
    try {
          HttpResponse response = httpClient.execute(httpGet, localContext);
          InputStream content = response.getEntity().getContent();
          BufferedReader buffer = new BufferedReader(new InputStreamReader(content));

          while ((text = buffer.readLine()) != null) {

              //Work with "text" here...
             //Split the string as you wish with "text.split();" function..

             }
         } catch (Exception e) {
            return e.getLocalizedMessage();
         }