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
Related
I'm having some trouble getting JSON response from Microsoft custom vision API (Optical Character Recognition API) when using Android Volley request.
I have used this approach with other API's without any problems, but for this API I cant get it to work.
String URL = "https://westcentralus.api.cognitive.microsoft.com/vision/v1.0/ocr";
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Getting License plate...");
pDialog.setCancelable(false);
pDialog.show();
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
JSONObject jsonBody = new JSONObject();
jsonBody.put("url", "https://upload.wikimedia.org/wikipedia/commons/thumb/a/af/Atomist_quote_from_Democritus.png/338px-Atomist_quote_from_Democritus.png");
final String requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pDialog.hide();
Log.i("VOLLEY", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}) {
#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 {
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("Ocp-Apim-Subscription-Key", "123124123123123123213");
return headers;
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
I'm getting this response back:
E/Volley: [2163] BasicNetwork.performRequest: Unexpected response code 400 for https://westcentralus.api.cognitive.microsoft.com/vision/v1.0/ocr
When using postman I'm not getting any errors.
So hope you can see what I'm doing wrong.
Let me know if you want me to elaborate on anything.
Thanks!
You have to replace StringRequest with JsonObjectRequest and get rid of the Content-type header.
This works for me:
final JSONObject jsonBody = new JSONObject();
jsonBody.put("url", "https://pbs.twimg.com/profile_images/808958766628605952/yB14UlXl_400x400.jpg");
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, URL, jsonBody,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println(response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
String readableError = "";
try {
readableError = new String(error.networkResponse.data, "utf-8");
System.out.println(readableError);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Ocp-Apim-Subscription-Key", "XXXXXXXX");
return headers;
}
};
note we had problems on older devices weirdly.
Was caused by the uploaded image being too big.
Api just returns 400 with no explanation.
ImageHelper class has code to resize image
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);
In my Android app I have a StringRequest and send it using Volley. The problem is that neither onResponse nor onErrorResponse get called!! I use JSONRequest in other part of my application and I have absolutely no problem with it.
What am I missing?
Here is one of the samples I tried
It's been bugging me for a couple of hours and I have no idea what is causing this. Any clue highly appreciated.
Here is the code:
public class AccountManagerProxy {
StringRequest req;
public void run() {
try {
String s1 = URLEncoder.encode("user", "UTF-8");
String s2 = URLEncoder.encode("pass", "UTF-8");
String uri = String.format("http://****/token?grant_type=password&username=%1$s&password=%2$s", s1, s2);
req = new StringRequest(Request.Method.GET, uri, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
VolleyLog.v("Response:%n %s", response);
Log.d("##", "##");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
Log.d("##", "##");
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
}
;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} Singleton.getInstance().getRequestQueue().add(req);
}
}
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();
}
...
well, i am new in this forum, please if you could help me in this. i searched but i could not find how to add headers to a volley request. i have this code and i want to add the accept-encoding:gzip and the api key. i would appreciate your help. here is the code:
type = "cafe";
url = "https://maps.googleapis.com/maps/api/place/search/json?location=" + Global.location + "&radius=500&types=" + type + "&sensor=true&key="+placesKey;
RequestQueue rq = Volley.newRequestQueue(context);
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
List<Review> reviews = new ArrayList<Review>();
reviews = Parsing.ParseReviews(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, error.toString(), Toast.LENGTH_SHORT).show();
}
});
rq.add(jsonRequest);
JsonObjectRequest jsObjectRequest = new JsonObjectRequest(
Request.Method.POST,
url,
jsonRequest,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, "Respuesta en JSON: " + response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error Respuesta en JSON: " + error.toString());
}
}
){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
//return super.getHeaders();
Map<String, String> params = new HashMap<>();
params.put("Content-Encoding", "gzip");
return params;
}
};
VolleySingleton.getInstance(context).addToRequestQueue(jsObjectRequest);
you can add headers in getHeaders().
Edit: How encode in gzip
JsonObjectRequest jsObjectRequest = new JsonObjectRequest(
/*same here*/
){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Content-Encoding", "gzip");
return params;
}
#Override
public byte[] getBody() {
try{
return Encode.gzip(super.getBody());
}catch(IOException e){
Log.d(TAG, e.getMessage());
return super.getBody();
}
}
};
VolleySingleton.getInstance(context).addToRequestQueue(jsObjectRequest);
Encode GZip
public static byte[] gzip(byte[] bytes) throws IOException{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = null;
try {
gzos = new GZIPOutputStream(baos);
gzos.write(bytes);
}finally {
if (gzos != null){
try{
gzos.close();
}catch (IOException ignore) {}
}
}
return baos.toByteArray();
}