Hy guys!
I have a jpg image stored on my device
and I want to sent it to server
(mywebsite.com/api.php). I would like to use volley library
because it is made by official android developers from google and I think they will add it to the sdk as soon as possible.
Right now I am using the folowing code to send Strings to the server:
postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
// code here for response
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// code here for error response
}
}
) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
// the POST parameters:
params.put("key", "myApiKey");
params.put("data","stringOfMyData");
return params;
}
};
How could I send the jpg to server with volley library? Every time I send something I need to send it together with the API key in order to receive information to server, so I cant change Map<String, String>
to Map<String, File>
because my API key is a string.
I have read that there is a solution to change my image to a byte[] array
and then converting it to a base64 string
format, but I would want to avoid this if possible.
Is there any other solution to send the image without converting it to a base64 string
?
Any reference or advice is welcome! Thanks in advance!
Files are sent using multipart
support in POST
request. It is same as in HTML forms as here.
Volley
doesn't have multipart support by default but it's flexible so you can extend its Request
class to implement your own version of multipart
.
You can find one implementation of MultipartRequest
class from this gist and just use in your program
https://gist.github.com/ishitcno1/11394069
You can consume this class something like this:
HashMap<String, String> params = new HashMap<String, String>();
String url = "YOUR POST URL";
String image_path = "your local image path";
params.put("your_extra_params", "value");
MultipartRequest multipartRequest =
new MultipartRequest(url, params, image_path, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.e(TAG, "Success Response: " + response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (error.networkResponse != null) {
Log.e(TAG, "Error Response code: " +
error.networkResponse.statusCode);
try {
}
if (error instanceof NetworkError) {
} else if (error instanceof ServerError) {
} else if (error instanceof AuthFailureError) {
} else if (error instanceof ParseError) {
} else if (error instanceof NoConnectionError) {
} else if (error instanceof TimeoutError) {
}
}
});
requestQueue.add(multipartRequest);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With