2011-09-19 59 views
0

我正試圖學習如何進行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; 
} 

}

+0

聽起來像你應該使用HttpGet而不是HttpPost。 –

+0

有什麼區別? – easycheese

+1

他們是不同的Http方法。因爲你的錯誤是關於Http方法,所以它似乎是適當的。 –

回答

1

您正在使用的方法是POST。託管該內容的HTTP應用程序期待其他內容 - 最有可能是GET。 Apache HTTP Client有一個類 - HTTPGet ...自然。 至於兩者的區別。主要區別在於GET方法將參數編碼爲URL的一部分(例如,您可能會注意到?apiAccessCode = api & parameter2 = something),而POST將內容作爲HTTP消息主體的一部分。 HTTP GET也限制爲256個字符。此外,用例意味着不同。 HTTP GET只能用於數據檢索,HTTP Post可用於更新內容。現在這些僅僅是用例,並不總是遵循。您實際上可以通過獲取請求更新內容。 HTH

+0

謝謝,GET工作。 – easycheese