【发布时间】:2011-09-19 15:40:41
【问题描述】:
我正在尝试学习如何进行 API 调用。我找到了一些教程并调整了代码以适合我,但出了点问题。
当我到达 result=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。
-
它们是不同的 Http 方法。由于您的错误与 Http 方法有关,因此它似乎是合适的。