2014-10-20 110 views
1

我複製了這個向谷歌方向API發送路由請求的整個類。 此類的函數以JSON的形式返回url中兩個給定點之間的路徑。向谷歌方向API發送請求以獲取路徑

import android.util.Log; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.json.JSONObject; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.UnsupportedEncodingException; 

public class JSONParser { 

    static InputStream is = null; 
    static JSONObject jObj = null; 
    static String json = ""; 
    // constructor 
    public JSONParser() { 
    } 
    public String getJSONFromUrl(String url) { 

     // Making HTTP request 
     try { 
      // defaultHttpClient 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost(url); 

      HttpResponse httpResponse = httpClient.execute(httpPost); 
      HttpEntity httpEntity = httpResponse.getEntity(); 
      is = httpEntity.getContent(); 

     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     try { 
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        is, "iso-8859-1"), 8); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 

      json = sb.toString(); 
      is.close(); 
     } catch (Exception e) { 
      Log.e("Buffer Error", "Error converting result " + e.toString()); 
     } 
     Log.d("JSON_RUTA", json); 
     return json; 

    } 
} 

對於一個未知的原因,在HttpResponse httpResponse = httpClient.execute(httpPost);應用程序崩潰,我明白,這是在請求被髮送到服務器爲主線,但我不知道爲什麼會這樣行了,我會如果你能幫助我,非常感謝你。

+0

你確定你傳遞任何一天網址是什麼? – 2014-10-20 21:23:22

+0

是的,這是函數: – itai 2014-10-20 21:31:09

+0

我在NetworkOnMainThread上下注 – njzk2 2014-10-20 22:23:38

回答

1

根據有關這個問題的第一個評論,是的,是這樣的功能:

public String makeURL (double sourcelat, double sourcelog, double destlat, double destlog){ 
     StringBuilder urlString = new StringBuilder(); 
     urlString.append("http://maps.googleapis.com/maps/api/directions/json"); 
     urlString.append("?origin=");// from 
     urlString.append(Double.toString(sourcelat)); 
     urlString.append(","); 
     urlString 
       .append(Double.toString(sourcelog)); 
     urlString.append("&destination=");// to 
     urlString 
       .append(Double.toString(destlat)); 
     urlString.append(","); 
     urlString.append(Double.toString(destlog)); 
     urlString.append("&sensor=false&mode=driving&alternatives=true"); 
     return urlString.toString(); 
    } 
+0

試試把你的調用Web服務放到線程裏面,如果你有錯誤,請把你的錯誤棧放在這裏 – 2014-10-22 09:12:12