Reputation: 973
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"
}
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
Upvotes: 1
Views: 1173
Reputation: 11
I'm a bit late to answer this, but I think it may help someone facing same problem. I search through all similar questions on SO, relating to PHP and Volley api but I didn't find any satisfying answer.
The problem is that you are sending data from the Volley library as content type
application/json
but your PHP script is expecting POST data as content type
application/x-www-form-urlencoded
In your PHP script, do this:
$_POST = json_decode(file_get_contents('php://input'), true);
if ( !empty($_POST['name']) ) {
$name = $_POST['name'];
echo $name;
}
Now if you check for
if( isset($_POST['name']) ){
echo "something";
}
it should work now
Basically just put this line
$_POST = json_decode(file_get_contents('php://input'), true);
before you call your 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);
});
Upvotes: 1
Reputation: 29614
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.
Upvotes: 0