Pass header and Params in same gson request using volley - android

I am trying to make PUT request using gson + volley where i have to send Header and Params both in the same request. I am getting a success response but data is not being sent to server. I am using the following code
public GsonRequest(int method,
String url,
Class<T> clazz,
Map<String, String> headers,
Map<String, String> params,
Listener<T> listener,
ErrorListener errorListener) {
super(method, url, errorListener);
this.clazz = clazz;
this.params = params;
this.listener = listener;
this.headers = headers;
mGson = new Gson();
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
return params != null ? params : super.getParams();
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers != null ? headers : super.getHeaders();
}
In Activity i am using above gson
private void updateProfile(String fname, String lname, String email, String mob) {
String tag_json_obj = "json_obj_req";
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", "JWT " + tinyDB.getString(Constants.MY_SHARED_PREF_TOKEN));
Log.d("Authorization---", "JWT " + tinyDB.getString(Constants.MY_SHARED_PREF_TOKEN));
String url = Constants.PATCH_USER+tinyDB.getString(Constants.MY_USER_ID);
Map<String, String> params = new HashMap<String, String>();
params.put("Content-type", "application/x-www-form-urlencoded");
params.put("first_name",fname);
params.put("last_name",lname);
params.put("email",email);
params.put("mobile_no", mob);
// url = url+"?first_name="+fname+"&last_name="+lname+"&email="+email+"&mob_no="+mob;
Log.d("URL -- ", "" + url);
GsonRequest<AddtoWishlistResponse> myReq = new GsonRequest<AddtoWishlistResponse>(
Request.Method.PATCH,
url,
AddtoWishlistResponse.class,
headers,
params,
createMyReqSuccessListener(),
createMyReqErrorListener());
AppController.getInstance().addToRequestQueue(myReq, tag_json_obj);
}

You can refer to the following sample code:
...
public GsonRequest(int method, String url, Class<T> clazz, Map<String, String> headers, String requestBody,
Response.Listener<T> listener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.mClass = clazz;
this.mHeaders = headers;
this.mRequestBody = requestBody;
this.mListener = listener;
this.mErrorListener = errorListener;
}
#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 {
try {
return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
mRequestBody, "utf-8");
return null;
}
}
Other methods such as parseNetworkResponse(), deliverResponse()... you should refer this Google training documentation - Implementing a Custom Request
For request body, you can refer the following:
Map<String, String> stringMap = new HashMap<>();
stringMap.put("key1", "value1");
stringMap.put("key2", "value2");
final String mRequestBody = buildRequestBody(stringMap);
...
private String buildRequestBody(Object content) {
String output = null;
if ((content instanceof String) ||
(content instanceof JSONObject) ||
(content instanceof JSONArray)) {
output = content.toString();
} else if (content instanceof Map) {
Uri.Builder builder = new Uri.Builder();
HashMap hashMap = (HashMap) content;
if (hashMap != null) {
Iterator entries = hashMap.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
builder.appendQueryParameter(entry.getKey().toString(), entry.getValue().toString());
entries.remove();
}
output = builder.build().getEncodedQuery();
}
}
return output;
}
Hope this helps!

Related

Volley StringRequest headers block parameters

My Volley code used to work properly like this:
StringRequest stringRequest = new StringRequest(method, URL, listener, errorListener){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//parameters are declared above this part of the code
return parameters;
}
};
Then I got Error 403 from a php file on server-side. People were suggesting adding headers to request. So I change my code to this:
StringRequest stringRequest = new StringRequest(method, URL, listener, errorListener){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//parameters are declared above this part of the code
return parameters;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError
{
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/form-data; charset=utf-8");
return headers;
}
};
After adding headers I was able to get rid of Error 403 but now Volley is not passing my parameters to server. Everything seem to be null.
I also tried to use getBodyContentType() instead of GetHeaders() but still same problem occurs.
Edit, the whole code:
public static void execute(final Request request, Context context){
if(queue == null)
queue = Volley.newRequestQueue(context);
final Map<String, String> parameters = new HashMap<String, String>();
for(int index = 0; index < request.getParameters().length; index++){
parameters.put(request.getParameters()[index].getName(), request.getParameters()[index].getValue());
}
int method;
switch (request.getRequestType()){
case GET: method = Method.GET; break;
case POST: method = Method.POST; break;
default: method = Method.POST; break;
}
String URL = request.getURL();
VolleyRequest newPostRequest = new VolleyRequest
(com.android.volley.Request.Method.POST, URL, parameters, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
request.onResponse(response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error.getMessage());
// TODO Auto-generated method stub
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "aapplication/x-www-form-urlencoded; charset=UTF-8");
return headers;
}
};
queue.add(newPostRequest);
}
server-side:
<?php
require_once 'connection.php';
$name = $_POST['name'];
$token = $_POST['token'];
if(strlen($name) < 4){
$feed = array("Result" => "Failed", "Message" => "Name must be at least four characters!");
echo json_encode($feed);
die;
}
$sql = $conn->prepare("SELECT name FROM user WHERE name = :name");
$sql->bindParam(':name', $name);
$sql->execute();
if($sql->rowCount() > 0){
$feed = array("Result" => "Failed", "Message" => "This name is already taken!");
echo json_encode($feed);
die;
}
$sql = $conn->prepare("INSERT INTO user (name, device_token) VALUES (:name, :token)");
$sql->bindParam(':name', $name);
$sql->bindParam(':token', $token);
$sql->execute();
$id = $conn->lastInsertId();
$feed = array("Result" => "Successful", "ID" => $id);
echo json_encode($feed);
?>
Follow this way. Use this custom request class.
public class VolleyRequest extends Request<JSONObject> {
private Response.Listener<JSONObject> listener;
private Map<String, String> params;
public VolleyRequest(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 VolleyRequest(int method, String url, Map<String, String> params,
Response.Listener<JSONObject> reponseListener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
#Override
protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
return params;
}
#Override
protected void deliverResponse(JSONObject response) {
listener.onResponse(response);
}
#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));
}
}
}
And implement like this way -
Map<String, String> params = new HashMap<String, String>();
params.put("param_1", "value_1");
params.put("param_2", "value_2");
VolleyRequest newPostRequest = new VolleyRequest
(Request.Method.POST, url, params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(CLASS_NAME, " Response: " + response.toString());
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/form-data; charset=utf-8");
return headers;
}
};
Volley.newRequestQueue(context.getApplicationContext()).add(newPostRequest);
Edit2: ServerSide code:
require_once 'connection.php';
$name = $_POST['name'];
$token = $_POST['token'];
if(strlen($name) < 4){
$feed = array("Result" => "Failed", "Message" => "Name must be at least four characters!");
echo json_encode($feed);
die;
}
$sql = $conn->prepare("SELECT name FROM user WHERE name = :name");
$sql->bindParam(':name', $name);
$sql->execute();
if($sql->rowCount() > 0){
$feed = array("Result" => "Failed", "Message" => "This name is already taken!");
echo json_encode($feed);
die;
}
$sql = $conn->prepare("INSERT INTO user (name, device_token) VALUES (:name, :token)");
$sql->bindParam(':name', $name);
$sql->bindParam(':token', $token);
$sql->execute();
$id = $conn->lastInsertId();
$feed = array("Result" => "Successful", "ID" => $id);
echo json_encode($feed);
Actually I had a similar problem as yours with my Volley StringRequest.
I needed to pass Authorization header as well as parameters to the server(CodeIgniter in my case)
I changed the Content type line from json to application/x-www-form-urlencoded; charset=UTF-8 and voila!!! It worked
i.e
//Setting Headers
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
headers.put("Authorization-token", func.getAuthorizationToken(getActivity()));
return headers;
}
//Adding parameters
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", "" + func.getSharedUserID(getActivity()));//Logged in user
Log.e("Passed User ID: ", func.getSharedUserID(getActivity()));
return params;
}

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

Volley With Get Request and parameters

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

Volley failing multipart form data request

I am trying to send multipart data to a server, this data includes also some images.
So i extended Request in this way:
public class MultipartImageRequest extends Request<String> {
private MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
private static final String STRING_PART_NAME = "text";
private final Response.Listener<String> mListener;
private final ArrayList<Bitmap> mFiles = new ArrayList<>();
private HashMap<String, String> mParams = new HashMap<>();
public MultipartImageRequest(String url, Response.ErrorListener errorListener, Response.Listener<String> listener, ArrayList<Bitmap> files, HashMap<String, String> params)
{
super(Method.POST, url, errorListener);
mListener = listener;
mFiles.addAll(files);
mParams = params;
}
private void buildMultipartEntity()
{
int i = 0;
for(Bitmap image : mFiles) {
/*Compress bitmap*/
ByteArrayOutputStream bos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 50, bos);
entityBuilder.addPart("image_" + i, new ByteArrayBody(bos.toByteArray(), "image_" + i));
i++;
}
StringBuilder paramsBuilder = new StringBuilder();
Iterator<Map.Entry<String, String>> paramIterator = mParams.entrySet().iterator();
while (paramIterator.hasNext()) {
Map.Entry<String,String> entry = paramIterator.next();
entityBuilder.addPart(entry.getKey(), new StringBody(entry.getValue(), ContentType.DEFAULT_TEXT));
}
}
#Override
public String getBodyContentType()
{
return "multipart/form-data; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError
{
buildMultipartEntity();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try
{
entityBuilder.build().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
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","multipart/form-data; charset=utf-8");
return params;
}
#Override
protected void deliverResponse(String response)
{
mListener.onResponse(response);
}
}
The problem is that if i set as a content type application/json it works and sends data to the server, but obviously the server gives me back an error 400 because it is expecting a multipart request, rather if i set the content type as multipart/form-data; charset=utf-8 like in the code above Volley just doesn't send the request and gives me an error 500.
I am using RequestBin to check my data and it confirms what i said above.
Also i am using a Rest Client and the request is working with it and on iphone too.
I found the solution on my own, it is important to pass a boundary to the request, otherwise the server will not be able to take our parameters.
It can be done replacing this code:
public MultipartImageRequest(String url, Response.ErrorListener errorListener, Response.Listener<String> listener, ArrayList<Bitmap> files, HashMap<String, String> params)
{
super(Method.POST, url, errorListener);
mListener = listener;
mFiles.addAll(files);
mParams = params;
}
with this one:
public MultipartImageRequest(String url, Response.ErrorListener errorListener, Response.Listener<String> listener, ArrayList<Bitmap> files, HashMap<String, String> params)
{
super(Method.POST, url, errorListener);
mListener = listener;
mFiles.addAll(files);
mParams = params;
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entityBuilder.setBoundary(BOUNDARY);
}
and remember to set the boundary string in your Content-Type:
#Override
public String getBodyContentType()
{
return "multipart/form-data; boundary=" + BOUNDARY + "; charset=utf-8";
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","multipart/form-data; boundary=" + BOUNDARY + "; charset=utf-8");
return params;
}

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