凌空没有发送POST参数

时间:2017-05-01 15:38:56

标签: php android api android-volley slim

我尝试使用PHP开发一个简单的rest API。我的API非常简单,它在POST请求中接收一个名称参数并在响应中打印相同的参数。

API在邮递员工作正常,但它不适用于Android。我无法弄清楚它是我的API还是客户端的问题。

端点: POST http://voidadd.com/api/v1/sendparam

参数:名称

这是我在邮差中得到的回应

public void startAlarm(Calendar c, int id){
    Toast.makeText(this, "Alarm in on", Toast.LENGTH_SHORT).show();
    Intent intent = new Intent(this,AlarmReciever.class);
    intent.putExtra("id",id);

    //int _id = (int)System.currentTimeMillis();

    PendingIntent pendingIntent = PendingIntent.getBroadcast(this,id,intent,PendingIntent.FLAG_ONE_SHOT);
    alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,c.getTimeInMillis(), 1000*60,pendingIntent);
    //alarmManager.set(AlarmManager.RTC_WAKEUP,c.getTimeInMillis(),pendingIntent);
}

Postman Response

但是我在从Android Studio进行API调用时会得到以下响应

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

我正在使用Volley如下:

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

makePostRequest方法

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

这是我处理API调用的PHP代码。我正在使用Slim框架

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

verifyRequiredParams function

$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);

  });

我在哪里做错了?我对Volley有很好的经验,我觉得客户方面的一切都很好。由于我是第一次编写rest API,我的PHP代码是否犯了错误?但它与邮递员合作。

如果我在邮递员中添加任何标题,我的API无效。

提前致谢

1 个答案:

答案 0 :(得分:0)

您正在发送new JSONObject(params)。根据邮递员的要求,你需要发送表格数据而不是json数据。

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

或者您必须接收json数据并在php服务器端解析它。