简体   繁体   English

Android中的Http GET Request错误

[英]Http GET Request error in android

I am trying to get a response from a http get request on android, without using the map activity, only sending a url request to get a response to a string. 我试图从android上的http get请求获取响应,而不使用map活动,仅发送url请求以获取对字符串的响应。

The url to get the response from: https://maps.googleapis.com/maps/api/distancematrix/json?origins=ashdod&destinations=yavne&key 从以下网址获取响应的网址: https : //maps.googleapis.com/maps/api/distancematrix/json?origins=ashdod&destinations=yavne&key

and the code I am trying is: 我正在尝试的代码是:

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

the problem is that it is throwing an exception when it reaches the connect. 问题是它在到达连接时抛出异常。

PS This is my first time with android so please be kind with me. PS这是我第一次使用android,所以请对我好一点。

When doing GET request, you do not need to do output. 在执行GET请求时,您不需要执行输出。

Just remove this line: 只需删除此行:

urlConnection.setDoOutput(true);

or you can simply change urlConnection.setDoOutput(true) to urlConnection.setDoOutput(false) 或者您可以简单地将urlConnection.setDoOutput(true)更改为urlConnection.setDoOutput(false)

Apart from this, you should also change this part of code to prevent garbled code: 除此之外,您还应该更改代码的这一部分以防止代码乱码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM