【发布时间】:2013-06-04 22:25:16
【问题描述】:
我正在尝试将数据从 Android 传递到我的 PHP 应用程序,但是一旦所有 $_POST 变量为空,POST 方法似乎无法正常工作。
我的 Android 活动的一部分:
String email = inputEmail.getText().toString();
String name = inputName.getText().toString();
String password = inputPassword.getText().toString();
String date = inputDate.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("date", date));
// Getting JSON Object
JSONObject json = jsonParser.makeHttpRequest(url, "POST", params);
现在,在我的 JSONParser.java 上:
// check for request method
if(method == "POST"){
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
httpPost.addHeader("content-type", "application/json");
HttpResponse httpResponse = httpClient.execute(httpPost);
Log.v("response code", httpResponse.getStatusLine().getStatusCode() + "");
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
我省略了代码的不相关部分,因为我实际上到达了服务器,只得到了空的 $_POST 变量。
奇怪的是,如果我删除这行...
httpPost.addHeader("content-type", "application/json");
...请求根本不起作用。
我正在关注本教程:AndroidHive
如果有人可以帮助我,我会很高兴!
【问题讨论】:
-
all $_POST variables are empty,当请求是application/x-www-form-urlencoded而不是application/json时填充$_POST变量 -
那么我该如何解决这个问题?如果我更改为: httpPost.addHeader("content-type", "application/x-www-form-urlencoded") 我会收到著名的错误:“解析数据时出错 org.json.JSONException: End of input at character 0” .提前致谢。
-
但是你还是会发送 json 对吧?
-
您可以发布通话的 JSON 响应吗?也许它以某种方式坏了
-
@Musa,如果我把 httpPost.addHeader("content-type", "application/json") 和 httpPost.addHeader("content-type", "application/x-www-form -urlencoded") 我得到了同样的错误(没有 $_POST)。