I have a server in tomcat and I am trying to make a request from my android device. All I get back is 415. I havent been able to replicate the error with fiddler by sending a defective Json. The server does not react to my request. I do have println() at every step just in case.
try {
params.put("userId", 2);
params.put("latitude", lon1);
params.put("longitude", lat1);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
errTextBox.setText(params.toString());
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, params.toString(),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
msg.setText(response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error: " + error.getMessage());
msg.setText("not ok " + error.getMessage());
}
}) {
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(jsonObjReq);
Not a dublicate because my request is done with a JsonObjectRequest. Also removing the charset did not help.
Well, I may have made a boo boo.
In my server software I was already parsing the recived string to Json.
So the is that I needed to send plain text...
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "text/plain; charset=utf8");
return headers;
Related
I'm calling a restful api on my android project and I used Volley and JsonObjectRequest, I thought that the third parameter of the JsonObjectRequest which is jsonRequest are the api parameters so I created a json object for that which in the end I only got errors. So is it common to directly add the api parameters on the url? instead of passing it on a json object? what is the third parameter for, it would be really helpful if someone can give me an example. And my last question is how do you get the entire json response instead of using response.getString("title") for each key.
//api parameters directly added on the url
String URL = "https://www.myapi.com/?param=sample¶m1=sample1";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String title = response.getString("Title");
Log.d("title", title);
} catch(Exception e){
Log.e("response error", e.toString());
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, error.toString());
}
});
Below your Response.ErrorListener() you need to add these two overrides:
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, error.toString());
}) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("param", "sample");
params.put("param1", "sample1);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/x-www-form-urlencoded; charset=UTF-8");
headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
return headers;
}
};
I can POST Map <String, String> to my server but it comes in & separated form.
I have used code from Send post request using Volley and receive in PHP
getParams() just doesn't work with JSONObject return type. Is it possible to send JSONObject as JSON only?
I want to send data as JSON that I will get using file_get_contents(php://input).
For this I have changed Content-Type to application/json; charset=utf-8.
The problem is using this way I get data in format of x=abc&y=def as it's Map<String, String> type and I want data in JSON format of {"x":"abc", "y":"def"}
It's different from above question because I want to POST data in JSON ONLY and not in MAP of String
Try this :
private void jsonObjReq() {
showProcessDialog();
Map<String, String> postParam= new HashMap<String, String>();
postParam.put("un", "xyz#gmail.com");
postParam.put("p", "somepasswordhere");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
Const.URL_LOGIN, new JsonObject(postParam),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
msgResponse.setText(response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideProgressDialog();
}
}) {
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
change header in your php too.
the easy way is this
final RequestQueue requestQueue = Volley.newRequestQueue(this);
final String url ="http://mykulwstc000006.kul/Services/Customer/Register";
Map<String, String> params = new HashMap<String, String>();
params.put("MobileNumber", "+97333765439");
params.put("EmailAddress", "danish.hussain4#das.com");
params.put("FirstName", "Danish2");
params.put("LastName", "Hussain2");
params.put("Country", "BH");
params.put("Language", "EN");
JsonObjectRequest req = new JsonObjectRequest(url, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
}){
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
String username ="eli#gmail.com";
String password = "elie73";
String auth =new String(username + ":" + password);
byte[] data = auth.getBytes();
String base64 = Base64.encodeToString(data, Base64.NO_WRAP);
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Authorization","Basic "+base64);
return headers;
}
};
requestQueue.add(req);
}
I'm trying to send a JsonObjectRequest to my server with some params, but seems like params doesn't arrive at the server. Before to post on SO I try all kind of suggestion found in google but no one works fine..
This is the code of my JsonObjectRequest:
RequestQueue queue = MySingleVolley.getInstance(ctx).
getRequestQueue();
JsonObjectRequest jsObjRequest = new JsonObjectRequest(method,url,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("REQUEST_JSON_TO_SERVER", "Success: " + response.toString());
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("REQUEST_JSON_TO_SERVER", "Error: " + error);
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
}
#Override
protected Map<String, String> getParams() {
return params;
}
};
MySingleVolley.getInstance(ctx).addToRequestQueue(jsObjRequest);
And these are my param and others:
String url = "url";
//create the hashMap of parameters
database_zappapp db = new database_zappapp(getApplicationContext());
db.open();
HashMap<String, String> params = new HashMap<>();
params.put("action","myAction");
params.put("nomeutente", db.getUsernameLogged());
params.put("token", token);
db.close();
//Send the request to the server
Global.RequestJsonToServer(getApplicationContext(), url, Request.Method.POST, params);
Thanks in advance for the help!
Edit 2
I've changed my params in this creating a string jsonBody:
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("action","gcmUserRegister");
jsonObject.put("nomeutente",db.getUsernameLogged());
jsonObject.put("token",token);
}catch(JSONException e){
e.printStackTrace();
}
String requestBody = jsonObject.toString();
db.close();
and my request like this with getBody():
JsonObjectRequest jsObjRequest = new JsonObjectRequest(method,url,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("REQUEST_JSON_TO_SERVER", "Success: " + response.toString());
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("REQUEST_JSON_TO_SERVER", "Error: " + error);
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
return headers;
}
#Override
public byte[] getBody() {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
requestBody, "utf-8");
return null;
}
}
};
But already didn't work! =(
Postman screen:
No user found means that it enter in the if statement and so it works.. with android i receive "result": "null"
The postman screen with app/json:
I've found the solution!
The problem was in the server not in the client, I was getting the data using POST but from the client I was sending a json object so my new php is:
$data = json_decode(file_get_contents('php://input'), true);
//echo "Action: ".$action;
//Registrazione del token
if($data['action'] == "gcmUserRegister"){
......
Thanks al lot to BKS!!!
Change this part of your code:
`JsonObjectRequest jsObjRequest = new JsonObjectRequest(method,url,null ...`
To this:
`JsonObjectRequest jsObjRequest = new JsonObjectRequest(method,url,yourparams..`
Reason: if you are using the default Volley constructors thats the way to send params to Server.
I am attempting a Volley POST request that passes in the parameter friends_phone_number_csv that should then return a JSON object. However in using the request below it simply notes:
E/Volley﹕ [4230] BasicNetwork.performRequest: Unexpected response code 500 for http://(ip-address):3000/getActivatedFriends.json
In testing this request in chromes POSTMAN I know the webservice is correct and should return a JSON object.
How can I make this work?
The POST request in app:
JsonObjectRequest getUserActiveFriends = new JsonObjectRequest(Request.Method.POST, "http://" + Global.getFeastOnline() + "/getActivatedFriends.json",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Parse the JSON:
try {
resultObject = response.getJSONObject("friends_match");
Toast.makeText(getApplicationContext(), resultObject.toString(), Toast.LENGTH_LONG).show();
// PARSE THE REST
//Log.v("USER ID", "The user id is " + userId);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}
) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("friends_phone_number_csv", contactsNumbers);
return params;
}
};
requestQueue.add(getUserActiveFriends);
You should add this code, when you post request and return json data, you should add content type "application/json; charset=utf-8" to http header.
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
I am trying to connect API url="api adress" which accepts two header types application/json to reponce in json and application/xml to reponce in xml. I need to hit JSON with json parameters and responce will be in json format too. Using android volley Post request with JsonObjectRequest setting headers using getHeaders it connects to server but getParams to set parameters does not work.
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
Constants.BASE_URL + Constants.LOGIN, null, response,
response_error) {
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
}
#Override
protected Map<String, String> getPostParams()
throws AuthFailureError {
// TODO Auto-generated method stub
Map<String, String> params = new HashMap<String, String>();
params.put("key", "value");
return params;
}
};
// implementation of listeners
Response.Listener<JSONObject> response = new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
Log.e("responce", response.toString());
// msgResponse.setText(response.toString());
hideProgressDialog();
}
};
Response.ErrorListener response_error = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error responce", error.getMessage());
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideProgressDialog();
}
};
//get params never get called
//i also tried alternative to send params but does not works.
Map<String, String> params = new HashMap<String, String>();
params.put("key", "value");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
Constants.BASE_URL + Constants.LOGIN, new JSONObject(params), response,
response_error) {
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
}
};
any type of help will be appretiated, Thanks in advance.
Volley will ignore your Content-Type setting, if you want to modify the content-type, you can override the getBodyContentType method :
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST, url,
new JSONObject(params), response, response_error) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
}
for why volley ignore your parameters? take a look at my another answer.
Volley JsonObjectRequest Post request not working
Take the other answer from that post wich starts with: You can create a custom JSONObjectReuqest