我正在尝试使用 android httpget 调用此 URL 以获得 json 方向数组:http://maps.googleapis.com/maps/api/directions/json?origin=Adelaide,SA&destination=Adelaide,SA&waypoints=optimize: true%7cBarossa+Valley,SA%7cClare,SA%7cConnawarra,SA%7cMcLaren+Vale,SA&sensor=false "
基本上这是我到目前为止所做的:
1)我首先创建了一个异步任务,以便调用谷歌方向并记录检索到的结果:
public class MyTask extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... params) {
InputStream is = null;
String result = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(params[0]);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
int lenght = (int) entity.getContentLength();
StringBuffer buffer = new StringBuffer(lenght);
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
Log.i("Result", result);
return result;
}
}
2)在主活动中,我将执行传递给它的异步任务 url :
MyTask t = new MyTask();
t.execute(urlString.toString());
其中 urlString 是一个 StringBuilder。我尝试以多种方式构建该地址,即使尝试使用 URLEncoder.encode(myUrl) 对其进行编码,但我总是得到一个异常,即http connectionjava.lang.NegativeArraySizeException 中的错误,我无法检索来自谷歌的 json 数据。如何正确格式化该网址?我的目标是达到与这个人相同的结果(在 json 部分):http: //blog.synyx.de/2010/06/routing-driving-directions-on-android-part-1-get-the -路线/
谢谢!