java - android中的Http GET请求错误

标签 java android httpurlconnection

我正在尝试从 Android 上的 http get 请求获取响应,而不使用 map Activity ,仅发送 url 请求来获取对字符串的响应。

获取响应的 URL: https://maps.googleapis.com/maps/api/distancematrix/json?origins=ashdod&destinations=yavne&key

我正在尝试的代码是:

HttpURLConnection urlConnection= null;
    URL url = null;
    String response = "";
    try {
        url  = new URL(urlString.toString());
        urlConnection=(HttpURLConnection)url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.connect();
        InputStream inStream = null;
        inStream = urlConnection.getInputStream();
        BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream));
        String temp = "";
        while((temp = bReader.readLine()) != null){
            //Parse data
            response += temp;
        }
        bReader.close();
        inStream.close();
        urlConnection.disconnect();

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

    try {
        JSONObject Jresponse = new JSONObject(response.toString());
        JSONArray rows = Jresponse.getJSONArray("rows");
        JSONObject rows_obj = (JSONObject) rows.get(0);
        JSONArray elems = rows_obj.getJSONArray("elements");
        JSONObject elems_obj = (JSONObject) elems.get(0);
        JSONObject dist = (JSONObject) elems_obj.get("distance");
        JSONObject dur = (JSONObject) elems_obj.get("duration");
        finalDistance = dist.getInt("value");
        finalDuration = dist.getInt("value");
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

问题是它在到达连接时抛出异常。

附注这是我第一次使用 Android,所以请善待我。

最佳答案

在进行GET请求时,不需要进行输出。

只需删除此行:

urlConnection.setDoOutput(true);

或者您可以简单地将 urlConnection.setDoOutput(true) 更改为 urlConnection.setDoOutput(false)

除此之外,还应该修改这部分代码,防止出现乱码:

BufferedReader bufferedReader = 
            new BufferedReader(new InputStreamReader(inStream, StandardCharsets.UTF_8));

关于java - android中的Http GET请求错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35830898/

相关文章:

android - 如何在一个查询室中的多对多关系中获取连接表中的额外列android

java - 无法使用Java的HttpURLConnection从Flickr API返回结果

java - 使用 httpurlconnection multipart/form-data 上传数组列表

java - Java 中的完整日期验证

java - 接受自定义比较器并将其应用于列表的方法。 java

java - 通过终端启动 PlantUML JAR 失败

java - 获取APNS服务器中未注册 token 的方法(使用Spring Server)

android - Android 应用程序中的 Google Plus key : What Key?

java - WebView 不渲染 HTML/gzip 内容,该内容是通过 shouldInterceptRequest() webViewClient 方法中的 HttpURLConnection 接收的

android - 在 Android 11 上构建文件资源管理器