Volley Post Request ClientError - android

I'm trying to send a POST Request with Volley to my server but it didnt work.
My GET-Requests are working fine and i also used postman to check if my rest service at the server works correctly.
I'm always getting a ClientError:
com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:190)
com.android.volley.NetworkDispatcher.processRequest(NetworkDispatcher.java:120)
com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:87)
I saw many different solutions here, but none of them worked out for my problem.
My StringRequest looks like this:
StringRequest addOrder = new StringRequest(
Request.Method.POST,
"http://myservice/rest/order",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String success = "DONE";
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
String test = error.toString();
//Log.e("Rest Response", error.toString());
}
})
{
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try{
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(clickedCocktail);
oos.flush();
}
catch(IOException ioe){
//Do Stuff by Exception
String exStr = ioe.getMessage();
}
return bos.toByteArray();
}
};
requestQueue.add(addOrder);
}

Related

Upload files with Volley custom body post request

I need to send 2 files to a server using volley library in Android.
There is an example of how it works well in Postman:
I need to reproduce this exactly POST call in android.
Please take a look of my code for now (which is not working):
JsonObjectRequest sr = new JsonObjectRequest(Request.Method.POST, URL, new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i("Response", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<>();
params.put("Urine", "test");
return params;
}
#Override
public Map<String, String> getHeaders() {
Map<String,String> params = new HashMap<>();
params.put("Authorization", "token");
return params;
}
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=utf-8";
}
#Override
public byte[] getBody() {
int size = (int) file.length();
byte[] bytes = new byte[size];
try {
BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
buf.read(bytes, 0, bytes.length);
buf.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bytes;
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
byte[] data = response.data;
String message = new String(data);
Log.i("parseNetworkResponse", String.valueOf(message));
return super.parseNetworkResponse(response);
}
};
How can I implement this using Volley library? Thanks.
Retrofit 2 in my opinion has been a much better and easier library to work with for file uploading.
Here is a nice and easy tut to work through. It should assist you.
Retrofit 2 - Multifile Uploading

receiving JSONobject allways failed with Voley

I have a problem when I try to use volley to communicate with a server (I created the server, so I can change a thing here too).
So when I use the stringRequest I have this problem:
my string contains 2 quotes, for example, the string looks like this: ""something""
while I send "something" and when I try to use this data like
if (response == "\"something\"")
do something
that doesn't work. I just can't use this string normally.
And when I try to use JsonObjectRequest I don't know why but I allways have this issue:
org.json.JSONException: Value {"name":"nofind"} of type java.lang.String cannot be converted to JSONObject
I tried to send this :
"{\"name\":\"nofind\"}",
"{'name':'nofind'}",
"{name:\"nofind\"}",
"{name:'nofind'}"
But It's always the same problem. I don't know why.
So please, if someone can help me. I will be very grateful
EDIT :
here my code :
JsonObjectRequest :
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, URL_SERVER+URL_IMAGE,
null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
resultsTextView.setText(response.toString());
snackbar.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR","error => "+error.toString());
resultsTextView.setText(R.string.ErrorServor);
snackbar.dismiss();
}
}){
#Override
public byte[] getBody(){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
faceBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
faceBitmap.recycle();
return byteArray ;
}
#Override
public String getBodyContentType() {
return "image/jpeg";
}
};
request.setRetryPolicy(new DefaultRetryPolicy(
0,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(request);
String request:
StringRequest request = new StringRequest(Request.Method.POST, URL_SERVER + URL_IMAGE,
this, this){
#Override
public byte[] getBody() {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
faceBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
faceBitmap.recycle();
return byteArray ;
}
#Override
public String getBodyContentType() {
return "image/jpeg";
}
};
request.setRetryPolicy(new DefaultRetryPolicy(
0,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(request);
}
#Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR","error => "+error.toString());
resultsTextView.setText(R.string.ErrorServor);
snackbar.dismiss();
}
#Override
public void onResponse(String response) {
try {
if (response != "nofind")
{
resultsTextView.setText(response);
NoButton.setVisibility(View.VISIBLE);
YesButton.setVisibility(View.VISIBLE);
}
else {
resultsTextView.setText(R.string.NoBack);
}
resultsTextView.setText(obj.toString());
} catch (JSONException e) {
e.printStackTrace();
System.out.println(e);
}
For each people who have the same problem as me.
To establish a communication between a WCF server and an Android application with Volley.
For the StringRequest the solution is written above.I just had to use .equals(MyString) in place of ==MyString.
But for the JsonObjectRequest the problem was on the server. In the BodyStyle parameter.
the Solution is I had to Wrappe Only the response.
So this is the function who worked for me.
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/NewUser",BodyStyle = WebMessageBodyStyle.WrappedResponse, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
dynamic NewUser(User user);
More information About the BodyStyle here :
RESTful web service body format

Uploading a File using Volley API via PUT method

I've been looking for a way to upload a file using Volley API using the PUT method. All I've seen so far are through MultiPart POST method which aren't applicable to my case.
Assuming I can't change anything on the server side and I'm stuck with using PUT. How do I achieve this in volley?
Note that I only have the url where to upload the file and the file itself.
For uploading image file add the following functions to your StringRequest object.
Here outputFileUri is the Uri of the file which you want to upload.
#Override
public String getBodyContentType() {
return "image/jpeg";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
InputStream inputStream = mContext.getContentResolver().openInputStream(outputFileUri);
byte[] b = new byte[8192];
for (int readNum; (readNum = inputStream.read(b)) != -1; ) {
bos.write(b, 0, readNum);
}
inputStream.close();
return bos.toByteArray();
} catch (Exception e) {
Log.d(TAG, e.toString());
}
return null;
}
use the basic concept of PUT method
url = "your URL";
StringRequest putRequest = new StringRequest(Request.Method.PUT, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", response);
}
}){
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String> ();
params.put("name", "file_name");
return params;
}
}; RequestQueue queue = Volley.newRequestQueue(this);
queue.add(putRequest);

error sending data to server using volley library

I have not used volley library much. i have read the tutorials. i want to send data to a url which which will enter that data in database. i have tried the following code but its not working. data is not entered in the database.
String url = "http://tipseducation.com/system/eadmin/insertschedule/";
StringRequest sr = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Valid Response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//error message
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("appt_name", ed_name);
params.put("appt_email", ed_email);
params.put("appt_contact", ed_contact);
params.put("appt_date", ed_date);
params.put("appt_time", ed_time);
params.put("appt_service", ed_spinner);
return params;
}
};
can anyone please help me. iam new to this
Instead of getHeaders, you should use getBody for your POST request.
You can refer to my following working sample code (replace my JSONObject and Url by yours). Hope this helps!
...
try {
RequestQueue queue = Volley.newRequestQueue(this);
jsonBody = new JSONObject();
jsonBody.put("Title", "Android Volley POST DATA Demo");
jsonBody.put("Author", "BNK");
jsonBody.put("Date", "2015/09/17");
requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(1, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// do something...
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// do something...
}
}) {
#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) {
e.printStackTrace();
return null;
}
}
};
queue.addToRequestQueue(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
...

Send raw post request using volley

I want to send post request with raw string rather than setting params using volley.
I have tried to override the getBody method in StringRequest like following:
#Override
public byte[] getBody() throws AuthFailureError {
return rawString.getBytes();
}
It won't even send the request and gives the error: com.android.volley.TimeoutError
Any help will be appreciated.
I got so ...
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(myReq);
...
StringRequest myReq = new StringRequest(Request.Method.POST,
server+"Login",
createMyReqSuccessListener(),
createMyReqErrorListener()) {
#Override
public byte[] getBody() throws com.android.volley.AuthFailureError {
String str = "{\"login\":\""+login+"\",\"password\":\""+pass+"\"}";
return str.getBytes();
};
public String getBodyContentType()
{
return "application/json; charset=utf-8";
}
};
...
private Response.Listener<String> createMyReqSuccessListener() {
return new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i(TAG,"Ski data from server - "+response);
}
};
}
private Response.ErrorListener createMyReqErrorListener() {
return new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i(TAG,"Ski error connect - "+error);
}
};
}

Categories

Resources