Volley With Get Request and parameters - android

I am trying to hit a url to get the Json Response Previously I was using HTTPURLConnection and its working perfectly fine so I am updating from HttpUrlConnection to Volley
The url I am trying to hit is following
http://162.13.137.145:8073/api/PageContent/GetPageContentsByName?PageName=About Us
But With Volley I am unable to get response
I have made a custom Class extended from Request but I am having following issue
error: org.json.JSONEXception: Value Access of type java.lang.String cannot be converted to JSONObject
Code for Custom Class is following
public class CustomGetPostRequest extends Request<JSONObject> {
private int mMethod;
private String mUrl;
Map<String, String> mParams= new HashMap<String ,String>();
private Response.Listener<JSONObject> mListener;
HashMap<String, String> headers = new HashMap<String, String>();
public CustomGetPostRequest(int method, String url, Map<String, String> params,
Response.Listener<JSONObject> reponseListener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
mMethod = method;
mUrl = url;
Log.d("Main URL",mUrl);
mParams = params;
mListener = reponseListener;
}
#Override
public String getUrl() {
if(mMethod == Request.Method.GET) {
StringBuilder stringBuilder = new StringBuilder(mUrl);
Iterator<Map.Entry<String, String>> iterator = mParams.entrySet().iterator();
int i = 1;
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
if(i == 1) {
stringBuilder.append("?" + entry.getKey() + "=" + entry.getValue());
} else {
stringBuilder.append("&" + entry.getKey() + "=" + entry.getValue());
}
iterator.remove(); // avoids a ConcurrentModificationException
i++;
}
mUrl = stringBuilder.toString();
Log.d("Converted URL",mUrl);
}
return mUrl;
}
#Override
protected Map<String, String> getParams()
throws com.android.volley.AuthFailureError {
Log.d("getParams","Called");
return mParams;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
// 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");
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) {
if (response.statusCode == 200)// Added for 200 response
return Response.success(new JSONObject(),HttpHeaderParser.parseCacheHeaders(response));
else
return Response.error(new ParseError(je));
}
}
#Override
protected void deliverResponse(JSONObject response) {
// TODO Auto-generated method stub
mListener.onResponse(response);
}
}
I also come to know that for Request type Get getParam() is not called so changed the url and directly added params in url
request for the Volley is following
CustomGetPostRequest getPostRequest = new CustomGetPostRequest(Request.Method
.GET,cachedURL,params,this,this);
getPostRequest.setTag(ResponseTag.CONTENT_PAGES);
mQueue.add(getPostRequest);
What I am missing here?

The only issue that I was facing after long debug is url was pushed with space and was not recognized a proper url so i changed url from
http://162.13.137.145:8073/api/PageContent/GetPageContentsByName?PageName=About Us
to
http://162.13.137.145:8073/api/PageContent/GetPageContentsByName?PageName=About%20Us
and it worked

Related

Volley POST Request with headers and raw json body

I am trying to make Post request from Android App that takes username and password in request body with content-type application/json in headers.
I tried changing content-type and how i send username passoword in body, but still no luck
public class MainActivity extends AppCompatActivity {
private Button Login;
private EditText loginEmail, loginPassword;
String URL = "https://localhost:8080/api/v1/auth";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loginEmail = (EditText)findViewById(R.id.etUsername);
loginPassword = (EditText)findViewById(R.id.etPassword);
Login = (Button)findViewById(R.id.btnLogin);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("username", loginEmail.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
try {
jsonObject.put("password", loginPassword.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
final String requestBody = jsonObject.toString();
Login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
startActivity(new Intent(MainActivity.this, LandingPage.class));
finish();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show();
NetworkResponse response = error.networkResponse;
if (error instanceof ServerError && response != null) {
try {
String res = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, "utf-8"));
// Now you can use any deserializer to make sense of data
JSONObject obj = new JSONObject(res);
Toast.makeText(MainActivity.this, res, Toast.LENGTH_LONG).show();
Log.i("MainActivity", res);
//use this json as you want
} catch (UnsupportedEncodingException e1) {
// Couldn't properly decode data to string
e1.printStackTrace();
} catch (JSONException e2) {
// returned data is not JSONObject?
e2.printStackTrace();
}
}
}
})
{
#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");
return params;
}
};
RequestQueue rQueue = Volley.newRequestQueue(MainActivity.this);
rQueue.add(request);
}
});
}
}
Post Request from Postman works perfectly fine but it throws Error 400 with Volley.
Below is the error I get in console
"errorSummary":"Bad request. Accept and/or Content-Type headers likely do not match supported values."
Try using a custom request and extending Request<JSONObject>:
CustomRequest class:
public class CustomRequest extends Request<JSONObject> {
private final Map<String, String> mHeaders;
private final JSONObject mBody;
private final Response.Listener<JSONObject> mResponseListener;
public CustomRequest(int method, String url, Map<String, String> headers, JSONObject body, Response.Listener<JSONObject> responseListener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.mHeaders = headers;
this.mBody = body;
this.mResponseListener = responseListener;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return mHeaders != null ? mHeaders : super.getHeaders();
}
#Override
public String getBodyContentType() {
return "application/json; charset=UTF-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
return mBody != null ? mBody.toString().getBytes(Charset.forName("UTF-8")) : super.getBody();
}
#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 | JSONException e) {
return Response.error(new ParseError(e));
}
}
#Override
protected void deliverResponse(JSONObject response) {
mResponseListener.onResponse(response);
}
}
Usage:
String url = "https://localhost:8080/api/v1/auth";
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("username", loginEmail.getText().toString());
jsonObject.put("password", loginPassword.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
CustomRequest customRequest = new CustomRequest(Request.Method.POST, url, headers, jsonObject, response -> {
// put your reponse listener code here
}, error -> {
// put your error listener code here
});
RequestQueue queue = Volley.newRequestQueue(context);
queue.add(customRequest);

getParams not calling in StringRequest Android

I am using StringRequest to send the Files to server. I am using the following code:
final MultipartEntityBuilder mHttpEntity = buildMultipartEntity(files_to_upload, params);
Response.Listener<String> rListner = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response != null) {
Intent intent = new Intent(Constants.ACTION_RESPONSE_RECEIVED);
intent.putExtra(Constants.RESPONSE, response);
intent.putExtra(SignupActivity.EXTRA_ACTION_RESPONSE, SignupActivity.EXTRA_SIGNUP_DATA);
LocalBroadcastManager.getInstance(MyApplication.getContext()).sendBroadcast(intent);
}
}
};
Response.ErrorListener errorListner = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Intent intent = new Intent(Constants.ACTION_RESPONSE_RECEIVED);
LocalBroadcastManager.getInstance(MyApplication.getContext()).sendBroadcast(intent);
if(error != null && error.getMessage() != null) {
// Toast.makeText(MyApplication.getContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
else {
Log.i(TAG, "postRequestToServer: onErrorResponse : error message null");
}
}
};
StringRequest jsonObjectRequest = new StringRequest(Request.Method.POST, url, rListner, errorListner)
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
return params;
}
// #Override
// public Map<String, String> getHeaders() throws AuthFailureError {
// return params;
// }
#Override
public String getBodyContentType() {
return mHttpEntity.build().getContentType().getValue();
}
//
#Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
mHttpEntity.build().writeTo(bos);
} catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
};
private MultipartEntityBuilder buildMultipartEntity(String files_to_upload, HashMap<String, String> params) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
String[] arr_files = files_to_upload.split("##");
for(int i = 0; i < arr_files.length; i++) {
String filePath = arr_files[i];
if(filePath == null || filePath.length() == 0)
continue;
File file = new File(filePath);
String extension = MimeTypeMap.getFileExtensionFromUrl(arr_files[i]);
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
builder.addBinaryBody("userfile", file, ContentType.create(mimeType), file.getName());
// builder.addPart("userfile", new FileBody(file));
}
try {
for (String key: params.keySet())
builder.addPart(key, new StringBody(params.get(key)));
} catch (UnsupportedEncodingException e) {
VolleyLog.e("UnsupportedEncodingException");
}
return builder;
}
But the issue is getParams is not being called. Server is expecting paramters, I tried to send using EntityBuilder but still I am having errors in sending the parameters.
Can anyone please let me know how can I upload files using
StringRequest with Parameters?
Your getParams() is not getting called because StringRequest.java inherits from Request.java. Now in Request.java, if you look at the getBody() method,
public byte[] getBody() throws AuthFailureError {
Map<String, String> params = getParams();
if (params != null && params.size() > 0) {
return encodeParameters(params, getParamsEncoding());
}
return null;
}
you can see getParams() is getting called from getBody() method. Now while making your request StringRequest jsonObjectRequest, you are overriding the getBody() method which means your getParams() will not get called. This is the reason why getParams() is not getting called.
EDIT
Create this custom volley request class that takes params inside the request constructor
public class CustomRequest extends Request<String> {
private Listener<String> listener;
private Map<String, String> params;
public CustomRequest(int method, String url, Map<String, String> params,
Listener<String> reponseListener, ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
protected Map<String, String> getParams()
throws com.android.volley.AuthFailureError {
return params;
};
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(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(String response) {
listener.onResponse(response);
}
}
Now send your request through this class. instead of overriding getParams(), just create a hashmap for your params, and pass them inside the constructor.
Use getparams and getHeader metods:
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("product_id", "4");
parameters.put("count", Productcount.getText().toString());
parameters.put("type", cashstatus);
parameters.put("description", "Matn bo'ladi");
parameters.put("phone_number", "946287009");
parameters.put("on_map", address);
return parameters;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", "Bearer " + token);
return headers;
}

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!

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;
}

Error trying send an image file with Volley?

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);

Categories

Resources