2016-03-06 107 views
0

我想從android的http獲取請求獲取響應,而不使用地圖活動,只發送url請求以獲取對字符串的響應。Http GET在android中的請求錯誤

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

的問題是,當它到達連接,它是拋出異常。

P.S.這是我第一次與機器人,所以請與我友善。

+0

您可以添加異常堆棧跟蹤 – bmavus

+0

和異常類 – maslan

回答

3

在做GET請求時,不需要輸出。

只是刪除這一行:

urlConnection.setDoOutput(true);

,或者你可以簡單地改變urlConnection.setDoOutput(true)urlConnection.setDoOutput(false)

除此之外,你也應該改變這部分代碼,以防止出現亂碼代碼:

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