我試圖調用此網址可與Android HTTPGET有方向的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「錯誤調用HTTPGET在安卓(谷歌檢索方向)
基本上這是我到目前爲止已經完成: )
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在主要活動中,我會執行異步任務傳遞給它的網址:
1)我第一次爲了調用谷歌的方向和登錄檢索結果創建的AsyncTask :
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-route/
謝謝!
logcat中的堆棧跟蹤應該指向它發生故障的那一行,發佈它; p –
它指向下面的一行StringBuffer buffer = new StringBuffer(lenght);所以看起來httpget的響應是空的(可能是因爲格式不正確的請求!)。 – jiraya85
但是它仍然不起作用! – jiraya85