我正在尝试使用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)我首先创建了一个asynctask,以便调用google指令并记录检索到的结果:
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)在主Activity中,我将执行异步任务,将url:
传递给它 MyTask t = new MyTask();
t.execute(urlString.toString());
其中urlString是StringBuilder。我尝试用几种方法构建该地址,即使尝试使用URLEncoder.encode(myUrl)对其进行编码,但我总是得到一个异常,这是 http connectionjava.lang.NegativeArraySizeException中的错误< / em> ,我无法从谷歌检索json数据。如何正确格式化该网址?我的目标是获得与这个家伙相同的结果(在json部分):http://blog.synyx.de/2010/06/routing-driving-directions-on-android-part-1-get-the-route/
谢谢!
答案 0 :(得分:1)
我终于明白了!我改变了调用google webservice的方式。基本上这部分:
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(params[0]);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
用另一种方式调用google webservice:
HttpURLConnection urlConnection = null;
url = new URL("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");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
is = urlConnection.getInputStream();
urlConnection.connect();
然后我“锁定”InputStreamReader中的输入流,缓冲读取器内的InputStreamReader,一切正常:
InputStreamReader inputStream = new InputStreamReader(is);
BufferedReader r = new BufferedReader(inputStream);
String line = null;
line = r.readLine();
while (line!=null){
Log.i("RESULT", line);
line = r.readLine();
}
通过这种方式,我可以记录所需的结果。我想了解的一件事是为什么httpclient不起作用,而httpURLConnection则改为。谁能帮我?
答案 1 :(得分:0)
只是删除有问题的代码,因为它没有在任何地方使用过吗?
//int lenght = (int) entity.getContentLength();
//StringBuffer buffer = new StringBuffer(lenght);