我正在使用Google距离矩阵api来获取位置之间的距离。所以我使用了这个查询:
String distanceofloc="https://maps.googleapis.com/maps/api/distancematrix/json?origins="+mylat+","+mylng+"&destinations="+placeloc+"&key=MY_BROWSER_KEY";
然后我用一个函数调用了一个函数来获取距离:
String dis=setDistance(distanceofloc);
这是我的 setDistance 功能:
public String setDistance(String url) throws URISyntaxException{
String dis=null;
StringBuilder placesBuilder = new StringBuilder();
//execute search
HttpClient placesClient = new DefaultHttpClient();
HttpResponse placesResponse=null;
//try to fetch the data
try{
HttpPost placesGet = new HttpPost(url);
try{
placesResponse = placesClient.execute(placesGet);
}catch(Exception e){
e.printStackTrace();
Log.v("PLACES", "exception thrown");
}
StatusLine placeSearchStatus = placesResponse.getStatusLine();
if (placeSearchStatus.getStatusCode() == 200) {
//we have an OK response
HttpEntity placesEntity = placesResponse.getEntity();
InputStream placesContent = placesEntity.getContent();
//create reader
InputStreamReader placesInput = new InputStreamReader(placesContent);
//use buffered reader to process
BufferedReader placesReader = new BufferedReader(placesInput);
//read a line at a time, append to string builder
String lineIn;
while ((lineIn = placesReader.readLine()) != null) {
placesBuilder.append(lineIn);
}}}
catch(Exception e){
e.printStackTrace();
Log.v("PLACES", "missing value");
}
try {
//parse JSON
//create JSONObject, pass stinrg returned from doInBackground
JSONObject distanceJSONObject = new JSONObject(placesBuilder.toString());
JSONArray rowArray = distanceJSONObject.getJSONArray("rows");
JSONObject rowsObject = rowArray.getJSONObject(0);//only one element in this array
JSONArray elementsArray = rowsObject.getJSONArray("elements");
JSONObject elementsObject = elementsArray.getJSONObject(0);//only one element in this array
if(elementsObject.isNull("distance")){
}
else{
JSONObject distanceObject = elementsObject.getJSONObject("distance");
if(!distanceObject.isNull("text"))
{
dis=distanceObject.getString("text"
}
}
}catch (JSONException e) {
e.printStackTrace();
}
return dis;
}
此处,异常被抛出
HttpPost placesGet = new HttpPost(url);
try{
placesResponse = placesClient.execute(placesGet);
}catch(Exception e){
e.printStackTrace();
Log.v("PLACES", "exception thrown");
}
任何人都可以告诉我网址是否有问题吗?感谢任何帮助。
答案 0 :(得分:0)
您不允许在主UI线程上执行任何网络io。 Android Framework提供了解决此限制的特定方法。您应该使用Worker Threads or AsyncTask来处理与您有关的所有与网络相关的事情。
编辑:
这是我最初的建议。它可能对其他人有用。
从我的头脑中,您是否拥有Manifest.xml
访问互联网的权限?
<manifest ...>
...
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>
这在尝试连接到任何服务器时会导致异常。