我正在尝试通过 POST 请求在 Android 中执行登录 AsyncTask,但在我的 PHP 代码中我没有收到任何参数,这是我的代码。
在我的 Android 代码中:
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(Constants.MY_URL);
post.setHeader("content-type", "application/json");
JSONObject data = new JSONObject();
data.put("user", mUsername);
data.put("password", mPassword);
StringEntity entity = new StringEntity(data.toString());
post.setEntity(entity);
HttpResponse resp = httpClient.execute(post);
String respStr = EntityUtils.toString(resp.getEntity());
在 PHP 代码中:
$params = $this->getService()->getRequest()->getActionParams();
echo json_encode($params);
但是在$params
中没有任何东西,也许我需要为请求设置其他headers
,或者我必须以不同的方式发送参数。有什么想法吗?
我也尝试过:
echo json_encode($_POST);
但我也一样,什么都没有。
提前致谢!
问候。
更新:
我刚试过:
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("user", mUsername));
pairs.add(new BasicNameValuePair("password", mPassword));
post.setEntity(new UrlEncodedFormEntity(pairs));
ResponseHandler<String> handler = new BasicResponseHandler();
final String response = client.execute(post, handler);
我得到了同样的回复,没有,我做错了什么?
最佳答案
使用nameValuepair向php发送数据
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("user",
txtUser.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("password",
txtPass.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost,
responseHandler);
关于php - 未从 Android POST 接收 PHP 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22755063/