Error trying send an image file with Volley? - android

I have an image that I'm trying send to my web service with others params using Volley library. The problem is I don't know how can I pass this image about the url using POST.
Looking for a solution I have founded any suggestions to use MultiPart and I'm trying implement that but still can't do this works.
I created other constructor in my Application, this constructor should receive a File but doesn't work also and HashMap doesn't accept File param
How can I do this ?
I'm trying this.
public class ApplicationController extends Request<JSONObject>{
private Map<String, String> headers;
private Map<String, String> params;
private Response.Listener<JSONObject> listener;
private File imageFile;
private MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
public ApplicationController(String url, Map<String, String> params, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.listener = listener;
this.params = params;
}
public ApplicationController(int method, String url, Map<String, String> params, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = listener;
this.params = params;
}
/** construtor to send image */
public ApplicationController(int method,
String url,
Map<String, String> params,
Response.Listener<JSONObject> listener,
Response.ErrorListener errorListener,
File file) {
super(method, url, errorListener);
this.listener = listener;
this.params = params;
this.imageFile = file;
}
protected Map<String, String> getParams() throws AuthFailureError {
return params;
};
public Map<String, String> getHeaders() throws AuthFailureError {
headers = new HashMap<String, String>();
String cred = String.format("%s:%s", BasicAuthenticationRest.USERNAME, BasicAuthenticationRest.PASSWORD);
String auth = "Basic " + Base64.encodeToString(cred.getBytes(), Base64.DEFAULT);
headers.put("Authorization", auth);
return headers;
};
private void buildMultipartEntity(){
mBuilder.addBinaryBody("", imageFile, ContentType.create("image/png"), imageFile.getName());
mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
mBuilder.setLaxMode().setBoundary("xx").setCharset(Charset.forName("UTF-8"));
}
#Override
public String getBodyContentType(){
String contentTypeHeader = mBuilder.build().getContentType().getValue();
return contentTypeHeader;
}
#Override
public byte[] getBody() throws AuthFailureError{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try{
mBuilder.build().writeTo(bos);
}catch (IOException e){
VolleyLog.e("IOException writing to ByteArrayOutputStream bos, building the multipart request.");
}
return bos.toByteArray();
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
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
protected void deliverResponse(JSONObject response) {
listener.onResponse(response);
}
}
Using
/** add an user and upload your foto(image) */
public ApplicationController insert(Usuario u, File imageFile, final UsuarioAdapter listener){
boolean insert = false;
HashMap<String, String> params = new HashMap<String, String>();
params.put("nome", u.getNome());
params.put("email", u.getEmail());
params.put("senha", u.getSenha());
params.put("tipo", "usuarios");
params.put("acao", "add");
params.put("device_tipo", "android");
params.put("device", AndroidReturnId.getAndroidId());
params.put("uploadedfile", imageFile);
ApplicationController apc = new ApplicationController(Method.POST, urlPost.toString(), params,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject obj) {
try {
if(obj.getString("cod").equals("999")){
listener.usuarioIsAdded(true);
}else{
listener.usuarioIsAdded(false);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError arg0) {
Log.e("ERROR METHOD:", "insert in UsuarioDAO: " + arg0.getLocalizedMessage());
}
}, File file);
return apc;
}

Encode the file to a base 64 encoded string and set that in the body (just make sure your server accepts this format!). Google how to do this in java, it's everywhere
params.put("uploadedfile", base64EncodedImageFile);

Related

Post Array using volley

I Want to post something like this [1,2,14,15] using volley to my PHP file where there's a SQL to retreive data from database.
Here my volley :
Map<String, String> userParams = new HashMap<String, String>();
listParams.put(TAG_IDS, all_ids);
CustomRequest myREquest= new CustomRequest(Request.Method.POST, URL, listParams,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
And in my PHP file i'll use a SQL something like this :
$liste=$_POST['IDS'] ;
$val= array_map('intval', $liste);
$new_liste = implode("','", $val);
$query = "SELECT * table WHERE IDS IN('".$new_liste ."')";
Here my CustomRequest
public class CustomRequest extends Request<JSONObject> {
private Response.Listener<JSONObject> listener;
private Map<String, String> params;
public CustomRequest(String url, Map<String, String> params, Response.Listener<JSONObject> reponseListener,
Response.ErrorListener errorListener){
super(Method.GET, url, errorListener);
this.listener=reponseListener;
this.params= params;
}
public CustomRequest(int methode, String url, Map<String, String> params, Response.Listener<JSONObject> reponseListener,
Response.ErrorListener errorListener){
super(methode,url,errorListener);
this.listener = reponseListener;
this.params = params;
}
protected Map<String, String> getParams()
throws com.android.volley.AuthFailureError{
return params;
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
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
protected void deliverResponse(JSONObject response) {
listener.onResponse(response);
}
}
Please help.
You should iterate your all_ids and put all of them in Map which will be send to the server. For example:
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
for(int i=0; i<all_ids.size(); i++) {
params.put(TAG_IDS + "[" + i + "]", all_ids.get(i).toString());
}
return params;
}

Getting 500 error for Volley PUT request android

CustomRequest.java
public class CustomRequest extends Request<JSONObject> {
private Listener<JSONObject> listener;
private Map<String, String> params;
private Map<String, String> headers;
public CustomRequest(String url,
Map<String, String> params,
Map<String, String> headers,
Listener<JSONObject> reponseListener,
ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.listener = reponseListener;
this.params = params;
this.headers = headers;
}
public CustomRequest(int method,
String url,
Map<String, String> params,
Map<String, String> headers,
Listener<JSONObject> reponseListener,
ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = reponseListener;
this.params = params;
this.headers = headers;
}
protected Map<String, String> getParams()
throws com.android.volley.AuthFailureError {
return params;
};
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers != null ? headers : super.getHeaders();
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
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
protected void deliverResponse(JSONObject response) {
// TODO Auto-generated method stub
listener.onResponse(response);
}
I am using request like this in my class:
Map<String, String> params = new HashMap<>();
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
Iterator it = params.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry) it.next();
Log.d(context.getClass().getCanonicalName(), "params - " + pairs.getKey() + ", " + pairs.getValue());
}
String url = AppConstants.SERVER_URL + mApi + "/" + mType+ "/" +mWord.getID();
Log.d("FinalUrl:->", url);
RequestQueue requestQueue = Volley.newRequestQueue(ActDrawAreaTwo.this);
CustomRequest jsObjRequest = new CustomRequest(Request.Method.PUT,
url,
params,
headers,
this.createRequestSuccessListener(),
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progress.dismiss();
}
});
RequestQueueHelper.addToRequestQueue(jsObjRequest, "");
I am getting error:
11-22 10:28:01.605 17921-18491/com.app.admin E/Volley: [3516] BasicNetwork.performRequest: Unexpected response code 500
Its a put request, its working in postman
According to your Postman screenshot, I suggest you use the following sample code:
String url = "http://...";
JSONObject jsonBody;
try {
jsonBody = new JSONObject();
jsonBody.put("ID", 1);
jsonBody.put("Name", "Word1");
jsonBody.put("ArabicName", "Arabic Word1");
// other key-value pairs...
JsonObjectRequest request = new JsonObjectRequest(Request.Method.PUT, url, jsonBody, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// do something
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// do something
}
});
queue.add(request);
} catch (JSONException e) {
e.printStackTrace();
}
Hope this helps!

Uploading image using Google Volley library

I am trying to upload an image using Volley library in android but no data is being send to the server side as the file is created but it does not contain any data.
public class ProfilePicSendReq extends Request<String>
{
private MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
private final Response.Listener<String> mListener;
private final File mImageFile;
protected Map<String, String> headers;
Context context;
public ProfilePicSendReq(Context cntxt, String url, Listener<String> listener, ErrorListener errorListener, File imageFile)
{
super(Method.POST, url, errorListener);
mListener = listener;
mImageFile = imageFile;
buildMultipartEntity();
context = cntxt;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError
{
headers = super.getHeaders();
if (headers == null
|| headers.equals(Collections.emptyMap()))
{
headers = new HashMap<String, String>();
}
headers.put("Accept", "text/plain");
return headers;
}
private void buildMultipartEntity()
{
mBuilder.addBinaryBody(mImageFile.getName(), mImageFile, ContentType.create("image/jpeg"), "profilePic");
mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
mBuilder.setLaxMode().setBoundary("xx").setCharset(Charset.forName("UTF-8"));
}
#Override
public String getBodyContentType()
{
String contentTypeHeader = mBuilder.build().getContentType().getValue();
return contentTypeHeader;
}
#Override
public byte[] getBody() throws AuthFailureError
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
mBuilder.build().writeTo(bos);
} catch (IOException e) {
Log.d("PicUploadMsg : ", "IOException writing to ByteArrayOutputStream bos, building the multipart request.");
}
return bos.toByteArray();
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response)
{
String result = new String(response.data);
return Response.success(result, HttpHeaderParser.parseCacheHeaders(response));
}
#Override
protected void deliverResponse(String response)
{
mListener.onResponse(response);
}
}
It is the famous sending Mulipart data using volley i have tried several time but no data appears to leave from the client side.

how to perform file upload using Volley in android?

I want to upload files(images,documents etc) from my android application to my server.I'm using Volley library for network calls in my application.
I'm using the following code to upload files but it is not performing any operation.(showing volley timeout error finally)
public class MultipartRequest extends Request<String> {
private MultipartEntity entity = new MultipartEntity();
private static final String FILE_PART_NAME = "file";
private final Response.Listener<String> mListener;
private final File mFilePart;
private String mStringPart,accessToken;
public MultipartRequest(String url, Response.ErrorListener errorListener, Response.Listener<String> listener, File file,String accessToken)
{
super(Method.POST, url, errorListener);
mListener = listener;
mFilePart = file;
this.accessToken = accessToken;
buildMultipartEntity();
}
private void buildMultipartEntity()
{
entity.addPart(FILE_PART_NAME, new FileBody(mFilePart));
try
{
entity.addPart("Content-Disposition", new StringBody("form-data"));
entity.addPart("dir_path", new StringBody("IzEzOjE3"));
}
catch (UnsupportedEncodingException e)
{
VolleyLog.e("UnsupportedEncodingException");
}
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null
|| headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
headers.put("Content-Type", "multipart/form-data");
headers.put("_pkta",accessToken);
return headers;
}
#Override
public String getBodyContentType()
{
return entity.getContentType().getValue();
}
#Override
public byte[] getBody() throws AuthFailureError
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try
{
entity.writeTo(bos);
}
catch (IOException e)
{
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response)
{
return Response.success("Uploaded", getCacheEntry());
}
#Override
protected void deliverResponse(String response)
{
mListener.onResponse(response);
}
}
please help me on how to implement file upload in android(either by volley or any other)
Try
public MultiPartRequest(String url, String filePath, Response.Listener<String> listener, Response.ErrorListener errorListener)
{
super(Method.POST, url, errorListener);
entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
file = new File(filePath);
mListener = listener;
buildMultipartEntity();
}
also, in my case I didn't override getHeaders, just passed other values with addPart, e.g:
entity.addPart("file", new FileBody(file, "image/jpeg")); // for image
entity.addPart("id", new StringBody(userid));
hope this helps.

Custom basic authentication with Volley?

I am trying create a custom BasicAuthentication with Volley. I have a class ApplicationController that I implemented methods getHeaders and works fine with all application, but now, I have a method that I need send other BasicAuthentication with other Parameters. To do it I am trying #Override the getHeaders() of class ApplicationController. It doesnt works and return a exception.
How can I do it ?
Exception
12-13 20:11:26.300 32356-430/br.com.application.apppackage E/Volley﹕ [157735] BasicNetwork.performRequest: Unexpected response code 400 for http://www.aplication.com.br/ServiceEndpointRest/WsChat/ws/salas/interact.json
12-13 20:11:26.305 32356-32356/br.com.application.apppackage E/ERROR METHOD:﹕ receiveMessage in ChatDAO: null
I'm trying this.
ApplicationController
public class ApplicationController extends Request<JSONObject>{
private Map<String, String> headers;
private Map<String, String> params;
private Response.Listener<JSONObject> listener;
private MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
private File mImageFile;
private Map<String, Object> imageParams;
public ApplicationController(String url, Map<String, String> params, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.listener = listener;
this.params = params;
}
public ApplicationController(int method, String url, Map<String, String> params, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = listener;
this.params = params;
}
protected Map<String, String> getParams() throws AuthFailureError {
return params;
};
public Map<String, String> getHeaders() throws AuthFailureError {
headers = new HashMap<String, String>();
String cred = String.format("%s:%s", BasicAuthenticationRest.USERNAME, BasicAuthenticationRest.PASSWORD);
String auth = "Basic " + Base64.encodeToString(cred.getBytes(), Base64.DEFAULT);
headers.put("Authorization", auth);
return headers;
};
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
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
protected void deliverResponse(JSONObject response) {
listener.onResponse(response);
}
}
#Override Header in Method receiveMessage
public ApplicationController receiveMessage(String emailAdversario){
///{\"Sala\":{\"usuario\":\"%#\",\"adversario\":\"%#\",\"atualizacao\":\"%#\",\"device\":\"%#\",\"device_tipo\":\"ios\"}}
urlPost.append("WsChat/ws/salas/interacao.json");
HashMap<String, String> params = new HashMap<String, String>();
params.put("usuario", BatalhaConfigs.USUARIO_EMAIL);
params.put("atualizacao", new Date().toString());
params.put("email", BatalhaConfigs.USUARIO_EMAIL);
params.put("device", AndroidReturnId.getAndroidId());
params.put("device_tipo", "android");
ApplicationController apc = new ApplicationController(Request.Method.POST,
urlPost.toString(),
params,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject obj) {
Log.i("RESPOSTA DA MENSAGEM: ", obj.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError arg0) {
Log.e("ERROR METHOD:", "receiveMessage in ChatDAO: " + arg0.getLocalizedMessage());
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
String cred = String.format("%s:%s", BatalhaConfigs.USUARIO_EMAIL, BatalhaConfigs.USUARIO_SENHA);
String auth = "Basic " + Base64.encodeToString(cred.getBytes(), Base64.DEFAULT);
headers.put("Authorization", auth);
return headers;
}};
return apc;
}

Categories

Resources