【发布时间】:2013-12-07 23:07:11
【问题描述】:
我正在尝试使用 Httppost 传递 JSONObject,但出现 406 错误 (SC_NOT_ACCEPTABLE)。
我尝试过 SO 中提出的不同解决方案,例如添加标题、使用 StringEntity,但对我来说没有任何效果。
谁能帮帮我?
ASYNCTASK CLASS:doInBackground 方法:
String URL = "www.myURL.com/myfile.php";
String key = "mykey";
mylibmandbhandler db = new mylibmandbhandler(ImExActivity.this);
JSONArray jason = db.exportDb(); // exportDb() returns JSONArray
db.close();
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 10000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
HttpConnectionParams.setSoTimeout(httpParameters, timeoutConnection);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
HttpResponse response = null;
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("key", key);
jsonObject.put("output", jason);
StringEntity output = new StringEntity(jsonObject.toString());
httppost.setEntity(output);
httppost.addHeader("Accept", "application/json");
httppost.addHeader("Content-type", "application/json");
response = httpclient.execute(httppost);
if(response.getStatusLine().getStatusCode()!=200){
return " E511: "+response.getStatusLine().getStatusCode()+": "+response.getStatusLine().toString();
}
HttpEntity entity = response.getEntity();
String responseBody = EntityUtils.toString(entity);
return responseBody;
} catch (Exception e) {
return "E509: Error in connection";
}
myfile.php
if(!isset($_POST['key'])){
echo "Denied.";
exit();
}else{
echo $post['output'];
exit();
}
LOGCAT: 没有错误,但是如果我打印 responseBody,我会在 logcat 中得到以下信息。但是,文件的存在没有问题,就像我发送普通字符串(不是JSON)一样,一切正常。
12-07 04:58:33.090: D/aaaa(1243): E511: 406: HTTP/1.1 406 Not Acceptable
12-07 04:58:33.130: D/aaaa(1243): <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
12-07 04:58:33.130: D/aaaa(1243): <html><head>
12-07 04:58:33.130: D/aaaa(1243): <title>406 Not Acceptable</title>
12-07 04:58:33.130: D/aaaa(1243): </head><body>
12-07 04:58:33.130: D/aaaa(1243): <h1>Not Acceptable</h1>
12-07 04:58:33.130: D/aaaa(1243): <p>An appropriate representation of the requested resource /myfile.php could not be found on this server.</p>
12-07 04:58:33.130: D/aaaa(1243): <p>Additionally, a 404 Not Found
12-07 04:58:33.130: D/aaaa(1243): error was encountered while trying to use an ErrorDocument to handle the request.</p>
12-07 04:58:33.130: D/aaaa(1243): <hr>
12-07 04:58:33.130: D/aaaa(1243): <address>Apache Server at www.myURL.com Port 80</address>
12-07 04:58:33.130: D/aaaa(1243): </body></html>
【问题讨论】: