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);
應用程序崩潰,我明白,這是在請求被髮送到服務器爲主線,但我不知道爲什麼會這樣行了,我會如果你能幫助我,非常感謝你。
你確定你傳遞任何一天網址是什麼? – 2014-10-20 21:23:22
是的,這是函數: – itai 2014-10-20 21:31:09
我在NetworkOnMainThread上下注 – njzk2 2014-10-20 22:23:38