dpiuqwwyu187975836 2017-05-01 15:38
浏览 97

凌空没有发送POST参数

I tried developing a simple rest API using PHP. My API is very simple, it receives a name parameter in POST request and prints the same in response.

API is working fine in postman but it is not working on Android. I can not figure out whether it is a problem with my API or with client side.

Endpoint: POST http://voidadd.com/api/v1/sendparam

Parameter: name

This is the response I'm getting in postman

{
  "code": 104,
  "message": "Parameter name received as: Amar"
}

Postman Response

But I'm getting following response when doing API call from Android Studio

{
  "error": true,
  "message": "Required field(s) name is missing or empty"
}

I'm using Volley as follows:

try{
            CommonUtils.showProgressBar();
            HashMap<String, String> param = new HashMap<String, String>();
            param.put("name", "Amar");

            VolleyUtils.makePostRequest(param, "http://voidadd.com/api/v1/sendparam", new VolleyPostRequestListener() {
                @Override
                public void onError(String error, String statusCode) {
                    CommonUtils.dismissProgressBar();
                    try {
                        JSONObject s = new JSONObject(error);
                        Log.e(TAG, s.toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, response.toString());
                    CommonUtils.dismissProgressBar();
                }
            });
        } catch (Exception e) {
            CommonUtils.writeLog(AppConstants.ERROR_LOG, TAG, e.getMessage());
            CommonUtils.dismissProgressBar();
        }

makePostRequest Method

public static void makePostRequest(HashMap<String, String> params, final String url, final VolleyPostRequestListener listener) {

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
                (Request.Method.POST, url, new JSONObject(params), new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        listener.onResponse(response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        try {
                            String body;
                            String statusCode = String.valueOf(error.networkResponse.statusCode);
                            if (error.networkResponse.data != null) {
                                try {
                                    body = new String(error.networkResponse.data, "UTF-8");
                                } catch (UnsupportedEncodingException e) {
                                    e.printStackTrace();
                                    body = "error";
                                }
                            } else {
                                body = "error";
                            }
                            listener.onError(body, statusCode);
                        }catch (Exception e) {
                            listener.onError("Exception","unknown");
                        }
                    }

                }) {

            @Override
            protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
                try {
                    String jsonString = new String(response.data,
                            HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
                    return Response.success(new JSONObject(jsonString),
                            HttpHeaderParser.parseCacheHeaders(response));
                } catch (UnsupportedEncodingException e) {
                    return Response.error(new ParseError(e));
                } catch (JSONException je) {
                    return Response.error(new ParseError(je));
                }
            }

        };
        AppController.getInstance().getRequestQueue().getCache().clear();
        AppController.getInstance().addToRequestQueue(jsonObjectRequest);
    }

This is my PHP code to handle API Call. I'm using Slim framework

$app->post('/sendparam', function() use ($app) {
            // check for required params
           verifyRequiredParams(array('name'));

            $response = array();

            $name = $app->request->post('name');

            $db = new DbHandler();

            $response["code"] = 104;
            $response["message"] = "Parameter name received as: " . $name;
            echoRespnse(200, $response);

  });

verifyRequiredParams function

function verifyRequiredParams($required_fields) {
    $error = false;
    $error_fields = "";
    $request_params = array();
    $request_params = $_REQUEST;
    // Handling PUT request params
    if ($_SERVER['REQUEST_METHOD'] == 'PUT') {
        $app = \Slim\Slim::getInstance();
        parse_str($app->request()->getBody(), $request_params);
    }
    foreach ($required_fields as $field) {
        if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) {
            $error = true;
            $error_fields .= $field . ', ';
        }
    }

    if ($error) {
        // Required field(s) are missing or empty
        // echo error json and stop the app
        $response = array();
        $app = \Slim\Slim::getInstance();
        $response["error"] = true;
        $response["message"] = 'Required field(s) ' . substr($error_fields, 0, -2) . ' is missing or empty';
        echoRespnse(400, $response);
        $app->stop();
    }
}

Where am I doing it wrong? I have had good experience with Volley and I feel everything is fine at client side. Since I'm writing rest API for the first time, did I made any mistake in my PHP code? But it is working with postman.

If I add any header in postman, my API is not working.

Thanks in advance

  • 写回答

1条回答 默认 最新

  • dongye7231 2017-05-01 15:56
    关注

    You are sending new JSONObject(params). According to the postman request, you need to send as form data not json data.

    StringRequest stringRequest = new StringRequest(Request.Method.POST,
    //...
     @Override
                protected Map<String,String> getParams(){
                    Map<String,String> params = new HashMap<String, String>();
                    params.put("name","Amar");
                    return params;
                }
    

    Or you will have to receive json data and parse it in your php server side.

    评论

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?