【发布时间】:2017-03-29 17:45:09
【问题描述】:
我正在尝试使用 Volley 从 Android 应用程序 向托管在我的服务器上的 PHP 脚本 发送 POST 请求。当我得到响应代码时,我得到了Code 200 Successfull,但 PHP 脚本中的$_POST 是空的。
我的安卓请求码:
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = getResources().getString(R.string.web_login);
JSONObject jsonBody = new JSONObject();
jsonBody.put("hello", "world");
jsonBody.put("username", username);
final String mRequestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.i("LOG_VOLLEY", response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("LOG_VOLLEY", error.toString());
}
}) {
@Override
public String getBodyContentType() {
return "text/plain; charset=utf-8";
}
@Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
return null;
}
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
try {
responseString = new String(response.data, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
这段代码工作正常,但是当我得到响应头时,它包含下一个 PHP 错误:
未定义索引:用户名
这是我的 php 脚本:
<?php
//Get post data from Android App
$name = $_POST['username'];
if (isset($name)){
$data = "OK";
header('Content-Type: text/plain');
echo $data;
}
?>
我做错了什么?
【问题讨论】:
-
您是否发布到那个 PHP 脚本的 URL?问题出在安卓端。
-
@mkaatman 是的,URL 是正确的,因为我在响应中收到了 php 错误。
-
在java中尝试
application/json; -
@Pavneet_Singh 还是一样的错误
标签: java php android http-post android-volley