java - 解析 http GET 响应体

标签 java android apache http

我正在连接一个网站及其 API 来检索数据。我下面的代码执行此操作并获取响应主体,但我如何解析该响应主体? 我是否必须创建自己的函数来搜索我想要的术语,然后获取每个术语的子内容?或者是否已经有一个我可以使用的图书馆可以为我做这件事?

private class GetResultTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
      String response = "";

        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet("https://api.bob.com/2.0/shelves/45?client_id=no&whitespace=1");
        try {
          HttpResponse execute = client.execute(httpGet);
          InputStream content = execute.getEntity().getContent();

          BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
          String s = "";
          while ((s = buffer.readLine()) != null) {
            response += s;
          }

        } catch (Exception e) {
          e.printStackTrace();
        }

      return response;
    }

    @Override
    protected void onPostExecute(String result) {
      apiStatus.setText(result); //setting the result in an EditText
    }
  }

响应正文

{
"id": 415,
"url": "http://bob.com/45/us-state-capitals-flash-cards/",
"title": "U.S. State Capitals",
"created_by": "bub12",
"term_count": 50,
"created_date": 1144296408,
"modified_date": 1363506943,
"has_images": false,
"subjects": [
    "unitedstates",
    "states",
    "geography",
    "capitals"
],
"visibility": "public",
"has_access": true,
"description": "List of the U.S. states and their capitals",
"has_discussion": true,
"lang_terms": "en",
"lang_definitions": "en",
"creator": {
    "username": "bub12",
    "account_type": "plus",
    "profile_image": "https://jdfkls.dfsldj.jpg"
},
"terms": [
    {
        "id": 15407,
        "term": "Montgomery",
        "definition": "Alabama",
        "image": null
    },
    {
        "id": 15455,
        "term": "Juneau",
        "definition": "Alaska",
        "image": null
    },

    {
        "id": 413281851,
        "term": "Tallahassee",
        "definition": "Florida",
        "image": null
    },
    {
        "id": 413281852,
        "term": "Atlanta",
        "definition": "Georgia",
        "image": null
    }
  ]
}

最佳答案

该数据格式是 JSON(JavaScript 对象表示法)。所以你只需要一个与安卓兼容的 JSON 解析器,比如 GSON ,你可以开始了。

关于java - 解析 http GET 响应体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16745317/

相关文章:

Apache 日志轮转脚本

java - 将 #text 从 getNodeName 转换为字符串

java - token "try"出现语法错误,请删除此 token

Java 替换变量

perl - 为什么我需要为 IIS 而不是 Apache 显式输出 HTTP header ?

java - 网页长时间打开抛出空指针异常

java - 如何在 Eclipse 运行时使用 GAE 模块的共享库?

android - AndroidX 迁移后找不到符号 DataBindingComponent

android - 无法创建任务 ':app:minifyReleaseWithR8' 。无法查询此提供程序的值,因为它没有可用的值

java - 如何为android项目制作背景音乐