Android http post不发送数据
首先,我收到状态码200。在php脚本中,我只是让代码将发送到服务器的内容发送给我(同时我尝试调试)。使用var\u dump$\u POST或$\u REQUEST,我收到一封空白电子邮件。如果我在$\服务器上运行foreach,我会返回一些数据,比如HTTP\u USER\u AGENT:apachehttpclient/UNAVAILABLE(java 1.4)和CONTENT\u LENGTH:9 我不明白为什么没有post数据?我是android新手,我在学习的过程中不断学习Android http post不发送数据,android,json,post,web,http-post,Android,Json,Post,Web,Http Post,首先,我收到状态码200。在php脚本中,我只是让代码将发送到服务器的内容发送给我(同时我尝试调试)。使用var\u dump$\u POST或$\u REQUEST,我收到一封空白电子邮件。如果我在$\服务器上运行foreach,我会返回一些数据,比如HTTP\u USER\u AGENT:apachehttpclient/UNAVAILABLE(java 1.4)和CONTENT\u LENGTH:9 我不明白为什么没有post数据?我是android新手,我在学习的过程中不断学习 Http
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(dest_url);
//httppost.setHeader("Accept", "application/json");
//httppost.setHeader("Content-type", "application/json");
//JSONObject json = new JSONObject();
// Add your data
//json.put("action", "login");
//json.put("username", "kermit");
//json.put("password", "123456");
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//nameValuePairs.add(new BasicNameValuePair("myjson", json.toString()));
nameValuePairs.add(new BasicNameValuePair("plswork", "hi"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
//StringEntity str_json = new StringEntity(json.toString());
//httppost.setEntity(str_json);
HttpResponse response;
response = httpclient.execute(httppost);
很可能是因为你的
httppost.setHeader("Content-type", "application/json");
application/json
不是HTTP POST表单提交的正常内容类型。考虑到您并不是真正发送json,而是一个标准POST实体(nameString=valueString),请尝试将其更改为
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded")
看看这是否能解决你的问题。或者更好的办法是将其全部移除
我在我的应用程序中使用了这段代码,它工作得非常好:
HttpPost httppost = new HttpPost(SERVER_URL);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("REQUEST", req));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = httpclient.execute(httppost);
HttpPost-HttpPost=newhttppost(服务器URL);
List nameValuePairs=新的ArrayList(1);
添加(新的BasicNameValuePair(“请求”,req));
setEntity(新的UrlEncodedFormEntity(nameValuePairs,“UTF-8”);
HttpResponse response=httpclient.execute(httppost);
本例中的响应是
text/xml
——但这不重要。我已经注释掉了这一行。我添加了您所说的内容,但没有任何区别。@I.am.Will只是出于好奇,尝试注释掉所有setHeader
行。只保留post的构造函数和设置实体,然后执行post。还要确保你的PHP代码是正确的——也许它确实收到了请求,但你没有正确地转发它。恐怕没有什么区别。我的php测试文件包含:@I.am.Will这是您的问题:var\u dump
是一个void
函数-它不返回任何内容,因此将其返回值赋给$string
将使该字符串为空。改为使用:$string=print\r($\u请求,true)
将标题设置为application/x-www-form-urlencoded
对我来说是个好办法。
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded")
HttpPost httppost = new HttpPost(SERVER_URL);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("REQUEST", req));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = httpclient.execute(httppost);