向谷歌方向API发送请求以获取路径
问题描述:
我复制了这个向谷歌方向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);
应用程序崩溃,我明白,这是在请求被发送到服务器为主线,但我不知道为什么会这样行了,我会如果你能帮助我,非常感谢你。
答
根据有关这个问题的第一个评论,是的,是这样的功能:
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
你确定你传递任何一天网址是什么? – 2014-10-20 21:23:22
是的,这是函数: – itai 2014-10-20 21:31:09
我在NetworkOnMainThread上下注 – njzk2 2014-10-20 22:23:38