I am new to Android Volley requests. I have managed to make post and get requests to the server and get the response.
public void getCardDetails() throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// response
Log.d("Response from server","Customer Account"+response);
try {
results = signInActivity.splitQuery(response);
String encodedMessage = results.get("encodedMessage");
String serverSignature = results.get("signature");
//Log.d("CustomerAccount","encodedMessage:"+ encodedMessage);
String decodeMessage = security.decodeBase64(encodedMessage);
Log.d("CustomerAccount","DecodedMessage"+ decodeMessage);
customerDetailsXML = decodeMessage;
try {
String computedSignature = security.hashMac(decodeMessage, signature_key);
int responseCode = xmlHandler.getResponseCode(decodeMessage);
Log.d("CustomerAccount","Response Code: "+responseCode);
if (responseCode == 1001){
getCardBalance();
Log.d("CustomerAccount","Success");
}
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-type", "application/x-www-form-urlencoded;charset=\"utf-8\"");
headers.put("Accept", "application/x-www-form-urlencoded");
headers.put("Cache-Control", "no-cache");
headers.put("Pragma", "no-cache");
headers.put("User-Agent", "Mozilla/5.0");
headers.put("Content-length", dataStream.toString());
return headers;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("encodedMessage", encodedMessage_req);
params.put("signature", signature);
return params;
}
};
Volley.newRequestQueue(this).add(postRequest);
}
The above request get the server response in a String XML format. I want to be able for the method in which i do the request to return the XML so i can manipulate it as i want out of the request method.
Any pointers on how to achieve this?
do something like this:
make an interface class:
public interface MyListener{
public void myMethod(String response);
}
change your method inputs: public void getCardDetails(MyListener listener)
in your public void onResponse(String response)
add this:
`listener.myMethod(response);`
Related
I have an API that takes a JSONArray as params and it gives a JSONObject as a response. The API is working fine but giving an error
com.android.volley.ParseError: org.json.JSONException: End of input at character 0 of
at com.android.volley.toolbox.JsonArrayRequest.parseNetworkResponse
as I receive the response.
JsonArrayRequest volleyRequest= new JsonArrayRequest(Request.Method.POST, url,
params, res -> {
try {
Log.d("TAG", "PostApiMethod: "+res);
} catch (JSONException e) {
Log.e("TAG", "PostApiMethod: ", e);
}
}, error -> {
Log.e(TAG, "PostApiMethod: ", error);
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
};
VolleySingleton.getInstance(context).addToRequestQueue(volleyRequest);
Is there any way to do this while using Volley.
you can use StringRequest and convert JSONArray to String as parameters and get result as String and map string to JSONObject like this code
JSONArray jsonBody=new JSONArray();
try {
/// add jSONObject inside JSONArray as example
JSONObject jsonObject=new JSONObject();
jsonObject.put("id",1);
jsonObject.put("name","test");
jsonBody.put(jsonObject);
} catch (Exception e) {
e.printStackTrace();
}
final String requestBody = jsonBody.toString();
StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
textView.setText(response.toString());
try {
JSONObject object=new JSONObject(response);
// do every thing using json object
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("error",error.toString());
}
}){
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
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;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
I recommended using retrofit library instead of Volley
I am trying to send a POST request with Volley in Android Studio. However, I would like to set some headers and a body. How can I do this?
In this case, the headers are id and key. Where should I add the body? I have tried to follow the numerous questions about these that are written in StackOverflow. However, it still seems like the headers and the body is not properly sent.
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "https://url.of.the.server";
JSONObject jsonBody = new JSONObject();
jsonBody.put("Content-Type", "application/json");
jsonBody.put("id", "oneapp.app.com");
jsonBody.put("key", "fgs7902nskagdjs");
final String requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
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;
}
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
params.put("id", "oneapp.app.com");
params.put("key", "fgs7902nskagdjs");
return params;
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
Log.d("string", stringRequest.toString());
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
Thank you very much for your help.
You are correctly setting the headers, you could try this
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "https://url.of.the.server";
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
// request body goes here
JSONObject jsonBody = new JSONObject();
jsonBody.put("attribute1", "value1");
String requestBody = jsonBody.toString();
return 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;
}
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
params.put("id", "oneapp.app.com");
params.put("key", "fgs7902nskagdjs");
return params;
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
Log.d("string", stringRequest.toString());
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
For example, if request body is
{
name: "name1",
email: "email1"
}
getBody method would be
#Override
public byte[] getBody() throws AuthFailureError {
JSONObject jsonBody = new JSONObject();
jsonBody.put("name", "name1");
jsonBody.put("email", "email1");
String requestBody = jsonBody.toString();
return requestBody.getBytes("utf-8");
}
I need to make an api request which.
Two headers :
Accept
Authorization
Five body params.
Number
Make
Model
Description
Plates
Through postman everything works great.
But when i try through android app i can't get through.
Note: Login through the same host works great so the setup its not the problem i think my main problem is in api call.
public void add(View view) {
RequestQueue queue = Volley.newRequestQueue(this);
String URL = "http://10.0.2.2:8000/api/trucks";
StringRequest request = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObj = new JSONObject(response);
// parse response
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse response = error.networkResponse;
String errorMsg = "";
if (response != null && response.data != null) {
String errorString = new String(response.data);
}
}
}
) {
#Override
public Map<String, String> getHeaders() {
HashMap<String, String> headers = new HashMap<>();
headers.put("Accept", "application/json");
headers.put("Authorization", "Bearer " + myToken);
return headers;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
TextInputEditText number = findViewById(R.id.textInputEditTextNumber);
TextInputEditText make = findViewById(R.id.textInputEditTextMake);
TextInputEditText model = findViewById(R.id.textInputEditTextModel);
TextInputEditText description = findViewById(R.id.textInputEditTextDescription);
TextInputEditText plates = findViewById(R.id.textInputEditTextPlates);
params.put("number", number.getText().toString());
params.put("make", make.getText().toString());
params.put("model", model.getText().toString());
params.put("description", description.getText().toString());
params.put("plates", plates.getText().toString());
return params;
}
};
queue.add(request);
}
Edit: by Solution #1.
public void add(View view) throws JSONException {
RequestQueue queue = Volley.newRequestQueue(this);
TextInputEditText number = findViewById(R.id.textInputEditTextNumber);
TextInputEditText make = findViewById(R.id.textInputEditTextMake);
TextInputEditText model = findViewById(R.id.textInputEditTextModel);
TextInputEditText description = findViewById(R.id.textInputEditTextDescription);
TextInputEditText plates = findViewById(R.id.textInputEditTextPlates);
JSONObject jsonObject = new JSONObject();
jsonObject.put("Number", number.getText().toString());
jsonObject.put("Make", make.getText().toString());
jsonObject.put("Model", model.getText().toString());
jsonObject.put("Description", description.getText().toString());
jsonObject.put("Plates", plates.getText().toString());
final String requestBody = jsonObject.toString();
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, "http://10.0.2.2:8000/api/trucks", jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//now handle the response
Toast.makeText(truck_add.this, response.toString(), Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//handle the error
Toast.makeText(truck_add.this, "An error occurred", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
}) { //this is the part, that adds the header to the request
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<String, String>();
params.put("Accept", "application/json");
params.put("Authorization", myToken);
return params;
}
};
queue.add(jsonRequest);
}
Postman :
When you want to pass the data through the body, you need to create a json object before string request.
try this way,
1. create a string url for request.
2. create json object for body data and pass data to it. Like,
JSONObject jsonObject= new JSONObject();
jsonObject.put("Number", address.getNumber());
jsonObject.put("Make", address.getMake());
jsonObject.put("Model", address.getModel());
jsonObject.put("Description", address.getDescription());
jsonObject.put("Plates", address.getPlates());
final String requestBody=jsonObject.toString();
3. After this, apply stringRequest.
4. Now, add below lines before header method and after error method.
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
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;
}
5. In your getHeaders() method, use Content-Type for "application/json" and for Authorization you must use only token without (Bearer).
Done.
public void add(View view) throws JSONException {
String URL = "http://10.0.2.2:8000/api/trucks";
//removed views initialization from here.
//you need to initialize views in oncreate() / oncreateView() method.
/*first create json object in here.
then set keys as per required body format with values
*/
JSONObject jsonObject = new JSONObject();
jsonObject.put("Number", number.getText().toString());
jsonObject.put("Make", make.getText().toString());
jsonObject.put("Model", model.getText().toString());
jsonObject.put("Description", description.getText().toString());
jsonObject.put("Plates", plates.getText().toString());
final String requestBody = jsonObject.toString();
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObj = new JSONObject(response);
// parse response
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse response = error.networkResponse;
String errorMsg = "";
if (response != null && response.data != null) {
String errorString = new String(response.data);
}
}
}
) { //this is the part, that adds the header to the request
//this is where you need to add the body related methods
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
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;
}
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
params.put("Authorization", myToken);
return params;
}
};
queue.add(jsonRequest);
}
Put Log in every method to check which method being executed and for possible error
If there is an error after this, then post error from logcat and we will solve it quickly.
my synchronous volley request to server have code 400 error but I don,t know why . I searched all questions but answers not work for me . I check API with postman and it work well .
public static String getResponce(final String Url, final List<NameValuePair> nameValuePairs) {
String resulte = "";
final RequestQueue requestQueue = Volley.newRequestQueue(MyApplication.getContext());
RequestFuture<String> future = RequestFuture.newFuture();
StringRequest request = new StringRequest(Request.Method.POST, Url, future, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
for (int i = 0 ; i < nameValuePairs.size() ; i++){
params.put(nameValuePairs.get(i).getName() , nameValuePairs.get(i).getValue());
}
Log.e("params" , params.toString());
return params;
}
};
requestQueue.add(request);
try {
resulte = future.get(30 , TimeUnit.SECONDS); // this will block
} catch (InterruptedException e) {
// exception handling
} catch (ExecutionException e) {
// exception handling
e.printStackTrace();
e.getMessage();
} catch (TimeoutException e) {
e.printStackTrace();
}
return resulte;
}
nameValuePairs is my request parametrs that add to hashmap in getParams() method.
E/Volley: [327] BasicNetwork.performRequest: Unexpected response code 400 for https://www.goldfishschool.com/api/users/authentication
this is my code please help me.
I am trying to send the image using the volley
public class ImageSendJsonObjectHeader extends JsonRequest<JSONObject> {
/* public ImageSendJsonObjectHeader (int method, String url, String requestBody, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(method, url, requestBody, listener, errorListener);
}
*/
public ImageSendJsonObjectHeader (String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener,
Response.ErrorListener errorListener) {
this(jsonRequest == null ? Method.GET : Method.POST, url, jsonRequest,
listener, errorListener);
}
public ImageSendJsonObjectHeader (int method, String url, JSONObject jsonRequest,
Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
errorListener);
// Log.i("Json Object",jsonRequest.toString());
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
//Log.i("Response parse","Yes");
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
//Log.i("Json String",jsonString);
System.out.println("Json String is"+ jsonString);
//Log.i("Response Complete",response.toString());
//Log.i("Response Data",response.data.toString());
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));
}
}
#Override
public String getBodyContentType() {
return "form-data";
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
//Log.i("Get Header","Enter");
HashMap<String, String> headers = new HashMap<String, String>();
//headers.put("Content-Type", "application/json; charset=utf-8");
//headers.put("Content-Type", "application/x-www-form-urlencoded");
Log.i("TOken is ", Constants.getTokenDB());
//System.out.println("Token Length is "+Constants.getTokenDB().length());
headers.put("x-access-token", Constants.getTokenDB());
//Log.i("Get Header","Exit");
return headers;
}
}
calling function:
private void uploadImage(File file){
//Showing the progress dialog
JSONObject jsonObject=new JSONObject();
Uri path = Uri.fromFile(file);
System.out.println("File is "+path);
//String image=getStringImage(bt);
System.out.println("Achaha "+path);
try {
jsonObject.put("Profile",path);
}catch (JSONException js){
js.printStackTrace();
}
Response.Listener listener=new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
try {
Boolean responseCond=response.getBoolean("success");
System.out.println( "Response "+responseCond);
String imagePath=response.getString("url");
System.out.println("Image Path "+imagePath);
}
catch (JSONException k)
{
Log.i("On Response",k.getMessage());
k.printStackTrace();
}
}
};
String image_url= Constants.url+"upload";
imageSendJsonObjectHeader customRequest=new imageSendJsonObjectHeader(image_url,jsonObject, listener, Constants.errorListener);
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(customRequest);
}
Tried way:
File file=new File(file_path);
File file=new File(file_path);
Uri path = Uri.fromFile(file);
send the bitmap
send the image as the string.
and pass the value in profile field.
Successful way using postman:
make it to base64 String
public static String imgToBase64(Bitmap bitmap) {
ByteArrayOutputStream out = null;
try {
out = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, out);
out.flush();
out.close();
byte[] imgBytes = out.toByteArray();
return Base64.encodeToString(imgBytes, Base64.DEFAULT);
} catch (Exception e) {
return null;
} finally {
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Ankur use lagecy in build.gradle useLibrary 'org.apache.http.legacy'