使用android studio检索Json数据

时间:2015-06-07 22:36:57

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

我非常擅长使用网络api,并且无法使用Riot Games'以JSON格式获取数据。 API。这是代码:

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权限。

2 个答案:

答案 0 :(得分:0)

你试过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());

哪里

  • 网址:是服务器的网址
  • postParemeters是ArrayList
  • 超时:带超时的整数参数

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

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));

希望这有效!!

答案 1 :(得分:0)

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