Android (Java) HTTP POST JSON 到服务器,但服务器告诉我没有看到 POST 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20484467/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android (Java) HTTP POST JSON to server, but the server tells me no POST variables were seen
提问by chris edwards
A member of my group project at university created this php for our application.
我大学小组项目的一名成员为我们的应用程序创建了这个 php。
if ( $_SERVER['REQUEST_METHOD'] != 'POST' ) {
header( 'HTTP/1.0 405 Method Not Allowed' );
output( 2, 'only POST is accepted; received ' . $_SERVER['REQUEST_METHOD'], true );
}
# catch empty POST requests
if ( count( $_POST ) == 0 ) {
output( 3, 'no POST variables were sent' );
}
My code passes the first test, but it is always failing this second test. with the error code '3' 'no POST variables were sent'
我的代码通过了第一个测试,但第二个测试总是失败。错误代码为“3”“没有发送 POST 变量”
This is the android code responsible for sending the POST request:
这是负责发送POST请求的android代码:
public void uploadToServer(Vector<PointOfInterest> pois) {
try {
JSONObject auth = new JSONObject();
JSONObject walk = new JSONObject();
JSONArray points = new JSONArray();
walk.put("walk name", "TEST NAME");
walk.put("walk desc short", "TEST SHORT");
walk.put("walk desc long", "TEST LONG");
for(int i = 0; i < pois.size(); i ++){
JSONObject location = new JSONObject();
location.put("name", pois.get(i).getName());
location.put("timestamp", 0);
location.put("lattitude",pois.get(i).getLattitude());
location.put("longitude",pois.get(i).getLongitude());
location.put("Description",pois.get(i).getDescription());
points.put(location);
}
auth.put("data", walk);
walk.put("locations", points);
auth.put("authorization","");
auth.put("hash","3b6decebf0bab0e0a08c18a94849d6df1e536d65");
auth.put("salt", "dave");
UploadASyncTask upload = new UploadASyncTask();
upload.execute(auth);
} catch (Exception e) {
e.printStackTrace();
}
}
private class UploadASyncTask extends AsyncTask<JSONObject, Void, Void>{
@Override
protected Void doInBackground(JSONObject...auth) {
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://project.chippy.ch/upload.php");
String json = "";
json = auth.toString();
StringEntity se = new StringEntity(json);
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPost.setEntity(se);
httpPost.setHeader("User-Agent", "WalkingTourCreator/1.0");
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
//httpPost.setHeader("data", json);
HttpResponse httpResponse = httpclient.execute(httpPost);
InputStream inputStream = httpResponse.getEntity().getContent();
String result = "";
if(inputStream != null){
result = convertInputStreamToString(inputStream);
}
else{
result = "Did not work!";
}
Log.d("RESULT", result);
}catch(Exception e){
Log.e("ERROR IN SEVER UPLOAD", e.getMessage());
}
return null;
}
Any ideas, or any obvious problems?
任何想法,或任何明显的问题?
The guy who made the php said this:
制作php的人是这样说的:
"POST needs key-value pairs (as far as I can tell); you'll need to send a key of "data" with the JSON as the contents."
“POST 需要键值对(据我所知);您需要发送一个带有 JSON 作为内容的“数据”键。”
As far as i am aware aren't i doing this?
据我所知,我不是这样做的吗?
I have followed a lot of posts on this site and various other bloggs etc, and they all seem to do a similar thing to what i am doing.
我在这个网站和其他各种博客等上关注了很多帖子,他们似乎都在做与我正在做的事情类似的事情。
Cheers Chris.
干杯克里斯。
采纳答案by chris edwards
Solved:
解决了:
HttpParams params = new BasicHttpParams();
//params.setParameter("data", auth);
HttpClient httpclient = new DefaultHttpClient(params);
HttpPost httpPost = new HttpPost("http://project.chippy.ch/upload.php");
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("data", auth.toString()));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams);
entity.setContentEncoding(HTTP.UTF_8);
httpPost.setEntity(entity);
was required instead of
需要而不是
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://project.chippy.ch/upload.php");
String json = "";
json = auth.toString();
StringEntity se = new StringEntity(json);
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPost.setEntity(se);
httpPost.setHeader("User-Agent", "WalkingTourCreator/1.0");
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
回答by Tristan Burnside
Your friend is correct you do need key-value pairs.
你的朋友是对的,你确实需要键值对。
StringEntity is just a raw string which is inserted into the http message data field. This must be properly formatted for the receiver to parse it.
StringEntity 只是一个原始字符串,它被插入到 http 消息数据字段中。这必须正确格式化以便接收者解析它。
Try using URLEncodedFormEntity which you will pass a list (of 1) key value pairs. The key will be whatever you want to call the parameter and the value will be the json string
尝试使用 URLEncodedFormEntity ,您将传递一个(1 个)键值对列表。键将是您想要调用的参数,值将是 json 字符串
EXAMPLE:
例子:
BasicNameValuePair param = new BasicNameValuePair("paramName",json);
List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>()
params.add(param);
URLEncodedFormEntity entity = new URLEncodedFormEntity(params);
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPost.setEntity(entity);
回答by Tony Maro
Actually try this answer. It appears that trying to send the auth as an entity string while also attaching a file (i.e. JSON) fails unless you create the auth header properly like so:
其实试试这个答案。似乎尝试将身份验证作为实体字符串发送,同时附加文件(即 JSON)会失败,除非您像这样正确创建身份验证标头: