【问题标题】:Retrieving Json data using android studio使用 android studio 检索 Json 数据
【发布时间】:2015-06-07 22:36:57
【问题描述】:

我对使用网络 API 非常陌生,并且在使用 Riot Games 的 API 获取 JSON 格式的数据时遇到了麻烦。代码如下:

public void readJSONFeed(String address) throws IOException {
    URL url = new URL(address);
    JSONObject jsonResponse = null;
    HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
    urlConnection.setRequestMethod("GET");
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(false);
    urlConnection.connect(); //Crashes here
    BufferedInputStream in = new BufferedInputStream(urlConnection.getInputStream());

我已经标记了代码崩溃的位置(如果您在之后评论所有内容并包括该内容,它就会起作用)。我认为问题可能是我正在使用的网络服务使用 https 并且我不知道如何使连接安全。我已将 Internet 权限添加到清单文件中。

【问题讨论】:

  • 你还没有连接 url.openConnection();?
  • 请说明抛出了什么异常类。正如 Mark Keen 所说,connect() 调用是不必要的,getInputStream() 将自动连接。但是,如果您在主线程上,任何网络操作都会抛出NetworkOnMainThreadException!那将是我的第一个嫌疑人。
  • 我做了,但是删除任何一个连接都不能解决错误。不过很好,我应该在粘贴代码之前仔细查看。
  • 是的,这是正确的,它是 NetworkOnMainThreadException。我查看了错误文档,看起来我现在希望能够弄清楚。谢谢!

标签: android json android-studio asp.net-web-api httpsurlconnection


【解决方案1】:

您是否尝试过使用 HttpClient? 这就是我连接到后端服务器的方式:

HttpPost httpPost = new HttpPost(url); //You can use HttpGet
httpPost.setEntity(new UrlEncodedFormEntity(postParameters));

HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,timeout);
HttpConnectionParams.setSoTimeout(httpParams,timeout);

HttpResponse response = httpClient.execute(httpPost);

String jsonToParse = EntityUtils.toString(response.getEntity());

在哪里

  • URL:是服务器的url
  • postParemeters 是 ArrayList
  • timeout:带超时的整数参数

如果您想使用 SSL 连接,您可以添加以下代码:

SchemeRegistry schemeRegistry = new SchemeRegistry();
                schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
                schemeRegistry.register(new Scheme("https",
                         SSLSocketFactory.getSocketFactory(), 443));

                HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

                SingleClientConnManager mgr = new SingleClientConnManager(
                        httpParams, schemeRegistry);
                httpClient = new DefaultHttpClient(mgr, httpParams);
                httpClient.setRoutePlanner(new DefaultHttpRoutePlanner(
                        schemeRegistry));

希望这行得通!

【讨论】:

    【解决方案2】:

    这是一个 NetworkOnMainThread 异常(https://developer.android.com/reference/android/os/NetworkOnMainThreadException.html 的文档)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      • 2020-05-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多