我正試圖學習如何進行API調用。我找到了一些教程,並修改了代碼,以適應我,但有些地方是錯誤的。API調用問題 - JSON(也是XML)Android
當我得到結果= sb.toString();我在我的字符串
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<title>Error 405 METHOD_NOT_ALLOWED</title>
</head>
<body><h2>HTTP ERROR 405</h2>
<p>Problem accessing /appInfo/getAllApplications. Reason:
<pre> METHOD_NOT_ALLOWED</pre></p><hr /><i><small>Powered by Jetty://</small></i><br/>
<br/>
</body>
</html>
下面我得到同樣的結果,如果我把我的頭按application/xml所以它不是一個JSON問題。我知道URL是正確的,因爲我的瀏覽器使用相同的URL獲取正確的數據。我認爲這個問題在我的BufferedReader中的某個地方,但我還沒有足夠的瞭解它還沒有找出問題的癥結所在。
public class APICall extends AsyncTask<String, Void, String>{
private static Context mCtx;
public APICall(Context ctx) {
mCtx = ctx;
}
@Override
protected String doInBackground(String... arg0) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mCtx);
String api = prefs.getString("API", "");
String url = "http://api.flurry.com/appInfo/getAllApplications?apiAccessCode=" + api;
//initialize
InputStream is = null;
String result = "";
JSONObject jArray = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setHeader("Accept", "application/xml");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
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");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//try parse the string to a JSON object
try{
jArray = new JSONObject(result);
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return null;
}
}
聽起來像你應該使用HttpGet而不是HttpPost。 –
有什麼區別? – easycheese
他們是不同的Http方法。因爲你的錯誤是關於Http方法,所以它似乎是適當的。 –