【问题标题】:Get JSON from URL - deprecated method?从 URL 获取 JSON - 不推荐使用的方法?
【发布时间】:2015-09-16 22:39:32
【问题描述】:

我一直在使用此代码从指定的 URL 获取 JSON,但今天我检查了它,其中的所有内容都已弃用。它仍然可以正常工作,但我想知道它的新方法是什么?

这是我所拥有的:

    @Override
    protected String doInBackground(String... params) {
        try {
            HttpClient client = new DefaultHttpClient();
            StringBuilder url = new StringBuilder("some url");
            HttpGet hg = new HttpGet(url.toString());
            HttpResponse hr = client.execute(hg);
            int status = hr.getStatusLine().getStatusCode();
            if (status == 200) {
                HttpEntity he = hr.getEntity();
                String data = EntityUtils.toString(he);
                jsonGet = new JSONObject(data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

不推荐使用的对象是HttpClientHttpGetHttpResponseHttpEntityEntityUtils

编辑:正如一些问题中所建议的那样

HttpClient client = HttpClientBuilder.create().build();

对我不起作用,因为我收到了HttpClientBuilder cannot be resolved

【问题讨论】:

  • 使用HttpUrlConnection
  • 想举个例子吗?

标签: android


【解决方案1】:

Apache httpClient 已被 api 级别 22 弃用,您可以阅读有关 this blog 的信息。

现在有一个新的安卓客户端,非常好。

但您可以改用okhttp(也可以使用反向兼容)。

编辑 检查这个link(URL.openConnection())。该博客于 2011 年发布,但据我所知,他们首先提到了那里的弃用。

【讨论】:

  • 这篇博文是 2011 年的,我不想使用外部 API
【解决方案2】:

首先你必须在谷歌上搜索好。

这是您的答案,希望对您有所帮助。

HttpClient 文档为您指明了正确的方向:

org.apache.http.client.HttpClient:

此接口在 API 级别 22 中已弃用。 请改用 openConnection()。请访问此网页了解更多详情。

表示你应该切换到java.net.URL.openConnection()

你可以这样做:

URL url = new URL("http://some-server");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");

// read the response
System.out.println("Response Code: " + conn.getResponseCode());
InputStream in = new BufferedInputStream(conn.getInputStream());
String response = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
System.out.println(response);

IOUtils 文档:Apache Commons IO
IOUtils Maven 依赖:http://search.maven.org/#artifactdetails|org.apache.commons|commons-io|1.3.2|jar

特别感谢fateddyanswer

【讨论】:

  • 为什么我必须下载额外的 jar 文件?这真的是 Android 想要我们做的吗?
  • 该文件的用途是将响应从InputStream 转换为String
  • 我不想使用外部 jar 文件
  • 然后使用DefaultHttpClient
猜你喜欢
  • 1970-01-01
  • 2011-02-27
  • 2014-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-05
  • 1970-01-01
相关资源
最近更新 更多