使用Volley向PHP脚本发送POST请求

时间:2017-03-29 17:45:10

标签: java php android http-post android-volley

我正尝试将 Android应用 POST请求发送到我服务器上托管的 PHP脚本。当我收到响应代码时,我得到Code 200 Successfull但PHP脚本中的$_POST为空。

我的Android请求代码:

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;
}   

?>

我做错了什么?

1 个答案:

答案 0 :(得分:0)

POST参数应该从getParams()发送。

尝试:

 try {
        final HashMap<String, String> params = new HashMap<>();
        params.put("username", username);

        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
                protected Map<String, String> getParams ()throws AuthFailureError {
                return params;
            }

                @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();
        }