HTTP-Headers not included in request made with Volley - java

I have the below request but for some reason the headers aren't being "attached" to the request? Please could you maybe assist me with this?
public void get(String servicesUrl, String end_tag_url) {
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url + servicesUrl + end_tag_url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error);
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("header1", "value");
params.put("header2", "value");
return params;
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
I get connection to the server but the is an auth failure because the headers aren't being implemented in the connection.
I have tested on a Chrome add-on called Advanced-Rest-Client and added the headers which worked.
I could add 2 of the headers to the URL but the 3rd one cannot be attached to the URL and needs to be a header?

When creating a request, override getHeaders(), like so:
new JsonObjectRequest(url, jsonRequest, listener, errorListener) {
#Override
public Map<String, String> getHeaders() {
Map<String, String> map = new HashMap<String, String>();
map.put("X-REST-API-Key", resources.getString(R.string.parse_api_key));
map.put("X-Application-id",
resources.getString(R.string.application_id));
if (sessionToken != null) {
map.put("X-Session-Token", sessionToken);
}
return map;
}
};

Related

why does the JSON response imperfect in Volley Android?

My complete response in Postman is the following but I can't get a complete response as JSON when using Volley android.
My volley code :
I have no problem sending a request but I show my logic that maybe was a problem with my code.
public void makeAssignment(final String token, HashMap<String,String> info_doc , List<Region> result, final OnMakeAssignment onMakeAssignment) {
HashMap<String, String> params = new HashMap<String, String>();
params.put("document_type", info_doc.get("type_doc"));
params.put("title", info_doc.get("title_doc"));
params.put("meter", info_doc.get("meter_doc"));
params.put("price", info_doc.get("price_frosh"));
params.put("mortgage_price", info_doc.get("vagozari_price_rahn")); // رهن
params.put("monthly_rent_price", info_doc.get("vagozari_price_ejareh")); // ejareh
params.put("address", info_doc.get("address"));
params.put("description", info_doc.get("vagozari_description"));
params.put("region[0]", "1");
if (result.isEmpty()){
params.put("region[0]", "all");
}else{
for (int i = 0; i < result.size(); i++) {
params.put("region["+i+"]", String.valueOf(result.get(i).getId()));
}
}
StringRequest stringRequest = new StringRequest(Request.Method.POST, Vars.MAKE_ASSIGNMENT,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
onMakeAssignment.onReceived(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NoConnectionError || error instanceof TimeoutError) {
context.startActivity(new Intent(context, NoInternet.class));
onMakeAssignment.onError(error.getMessage());
}
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
// params.put(Vars.KEY_AUTH, Vars.AUTH);
params.put(Vars.KEY_AUTH, token);
params.put(Vars.KEY_USERNAME, Vars.USERNAME);
params.put(Vars.KEY_PASSWORD, Vars.PASSWORD);
return params;
}
#Nullable
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
}
The JSON response details are imperfect when I call this method with the Volley library but a response in the Postman is complete. so finally o don't know why this happens because it isn't a problem in requests when using PostMan. so my android Logcat gets back this response when running a method request but unfortunately it isn't the same as the response Postman.
I/resewssssssss: {"clients":[{"id":44,"name":null,"mobile":null,"mobile_confirmed":0,"invited":0,"device_id":"null","firebase_token":"","device_serial":"","credit":"0","city_id":null,"region_id":null,"state_id":null,"api_token":"Basic LUnrhilQIWfdY6YQr6lxWCuZ8TAtNs4ailckURW6MG","client_type":1,"created_at":"2020-07-22T12:27:41.000000Z","updated_at":"2020-07-22T12:27:41.000000Z","credit_date":null,"description":null,"assignment_active":1,"assignment_reason":null,"visited":null,"property_request_active":1,"property_request_reason":null,"properties_count":6,"client_regions":[{"id":69,"client_id":44,"region_id":1}]},{"id":43,"name":null,"mobile":null,"mobile_confirmed":0,"invited":0,"device_id":"null","firebase_token":"","device_serial":"","credit":"0","city_id":null,"region_id":null,"state_id":null,"api_token":"Basic jwfz4Ll1YYE3oG4ZFDtAQEgufW4q2ZozEr3LUJU0q58","client_type":1,"created_at":"2020-07-22T11:59:49.000000Z","updated_at":"2020-07-22T11:59:49.000000Z","credit_date":null,"description":null,"assignment_active":1,"assignment_reason":null,"visited":null,"property_request_active":1,"property_request_reason":null,"properties_count":2,"client_regions":[{"id":68,"client_id":43,"region_id":1}]},{"id":31,"name":null,"mobile":null,"mobile_confirmed":0,"invited":0,"device_id":"null","firebase_token":"","device_serial":"","credit":"0","city_id":null,"region_id":null,"state_id":null,"api_token":"Basic SI3FWNH1mxg8N4JL0HEu45nEqlUBtEv
JQbRdmpuR4CeKcJ0","client_type":1,"created_at":"2020-07-20T16:01:48.000000Z","updated_at":"2020-07-20T16:01:48.000000Z","credit_date":null,"description":null,"assignment_active":1,"assignment_reason":null,"visited":null,"property_request_active":1,"property_request_reason":null,"properties_count":1,"client_regions":[{"id":51,"client_id":31,"region_id":1}]},{"id":33,"name":null,"mobile":null,"mobile_confirmed":0,"invited":0,"device_id":"null","firebase_token":"","device_serial":"","credit":"0","city_id":null,"region_id":null,"state_id":null,"api_token":"Basic nOwhIwlowhqgQUXEHH8heXSmM
iJOqNEoJiVb6TKwO381Yp","client_type":1,"created_at":"2020-07-20T20:05:22.000000Z","updated_at":"2020-07-20T20:05:22.000000Z","credit_date":null,"description":null,"assignment_active":1,"assignment_reason":null,"visited":null,"property_request_active":1,"property_request_reason":null,"properties_count":1,"client_regions":[{"id":53,"client_id":33,"region_id":1},{"id":54,"client_id":33,"region_id":118}]},{"id":34,"name":null,"mobile":"09123456789","mobile_confirmed":0,"invited":0,"device_id":"null","firebase_token":"","device_serial":"","credit":"0","city_id":null,"region_id":null,"state_id":null,"api_token":"Basic DkCrb8tzrt5FKldXon0xm8d
e2fLpugea61lVRnOR3IATSfb","client_type":1,"created_at":"2020-07-20T20:51:55.000000Z","updated_at":"2020-07-21T18:08:46.000000Z","credit_date":null,"description":null,"assignment_active":1,"assignment_reason":null,"visited":null,"property_request_active":1,"property_request_reason":null,"properties_count":1,"client_regions":[{"id":55,"client_id":34,"region_id":1}]},{"id":1,"name":"\u06a9\u0627\u0631\u0628\u0631 \u062a\u0633\u062a","mobile":null,"mobile_confirmed":0,"invited":0,"device_id":null,"firebase_token":null,"device_serial":null,"credit":"0","city_id":1,"region_id":null,"state_id":1,"api_token":"Basic a142pbR0LGvfaZFi6333ZIj5pghgyzsFmGiNvn4k4CwzRi6g","client_type":1,"created_at":"2020-07-02T13:16:26.000000Z","updated_at":"2021-05-21T02:48:02.000000Z","credit_date":"2021-05-18","description":"ttewtwt","assignment_active":1,"assignment_reason":null,"visited":null,"property_request_active":1,"property_request_reason":null,"properties_count":0,"client_regions":[{"id":1,"client_id":1,"region_id":1},{"id":2,"client_id":1,"region_id":2},{"id":3,"client_id":1,"region_id":3}]},{"id":9,"name":null,"mobile":null,"mobile_confirmed":0,"invited":0,"device_id":"null","firebase_token":"","device_serial":"","credit":"0","city_id":null,"region_id":null,"state_id":null,"api_token"

How do you obtain a Auth token using webView in android?

I need to receive the token on my Android aplication..
I created and API on laravel, and i need to receive a token, but i dont know how to do it on android.
It would be difficult to read a token into a WebView and then try to extract it from the WebView. Typically, you just make an HTTP Request to an API method to get the token, then store the token for later use. Here is an example of doing that, which doesn't involve using the WebView:
// You need a URL to an API method that will return the token
if (apiToken.length() == 0) {
getToken("https://mycompany.com/account-services/api/v1/token");
}
private void getToken(String url) {
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
// Response JSON contains the token
JSONObject obj = new JSONObject(response);
apiToken = obj.getString("access_token");
// Save the token in the shared appPrefs so it can be referenced in other classes
SharedPreferences appPrefs = getSharedPreferences("appPreferences",MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = appPrefs.edit();
prefsEditor.putString("apiToken", apiToken);
prefsEditor.commit();
} catch (JSONException e) {
Log.e("myapp", "JSONException Error: " + e.getLocalizedMessage());
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("myapp", "Response Error: " + error.toString());
}
}) {
#Override
protected Map<String, String> getParams()
{
// Most Token API methods have their own secret user id and password
Map<String, String> params = new HashMap<String, String>();
params.put("grant_type", "password");
params.put("username", "apiusername");
params.put("password", "apipassword");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
// This API expects the parameters in the form of "grant_type=password&username=apiusername&password=apipassword"
headers.put("Accept", "application/x-www-form-urlencoded; charset=UTF-8");
headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
return headers;
}
};
// the Request Queue has been declared in the Application object on app startup
MyApplication.getInstance().addToRequestQueue(postRequest);
}

How to make GET request to Yelp api using volley?

I am using Volley to make get request to Yelp Api and keep getting "BasicNetwork.performRequest: Unexpected response code 400 for https://api.yelp.com/v3/businesses/search" error. I made GET request on Postman using the same parameters and headers and it worked just fine. Yelp has released their new API v3 recently,so I did not find any useful similar problem on stackoverflow.
StringRequest stringrequest = new StringRequest(Request.Method.GET,
"https://api.yelp.com/v3/businesses/search",
new Response.Listener<String>(){
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
}catch(JSONException e){
e.printStackTrace();
}
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
progressDialog.hide();
Toast.makeText(getApplicationContext(),error.getMessage(),Toast.LENGTH_LONG).show();
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers = new HashMap<>();
//headers.put("Content-Type","application/x-www-form-urlencoded");
headers.put("Authorization",[Bearer myToken]);
return headers;
}
#Override
protected Map<String,String> getParams() throws AuthFailureError{
Map<String, String> params = new HashMap<>();
params.put("latitude",latitude);
params.put("longitude",longitude);
params.put("radius","15");
return params;
}
};
RequestHandler.getInstance(this).addToRequestQueue(stringrequest);

Android post request with non key pair

Below is my currently working code to switch on a light with my home automation system. I am upgrading to a new system and it needs a modified post command. Currently I think this sends the key pair "lightswitch1=ON". I need it to only send "ON" but I am not sure how to do this. Below is the CURL command that works.
public void turnonlight() {
String url = "http://example.com:8090/CMD";
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Toast.makeText(MjpegActivity.this,response,Toast.LENGTH_LONG).show();
//This code is executed if the server responds, whether or not the response contains data.
//The String 'response' contains the server's response.
}
},
new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(MjpegActivity.this,error.toString(),Toast.LENGTH_LONG).show();
//This code is executed if there is an error.
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
MyData.put(lightswitch1 "ON"); //Add the data you'd like to send to the server.
return MyData;
}
};
RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
MyRequestQueue.add(MyStringRequest);
}
curl -X POST --header "Content-Type: text/plain" --header "Accept: application/json" -d "ON" "http://example.com:8090/CMD"
The following should be working with Volley :
String url = "http://example.com:8090/CMD";
StringRequest myStringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/json");
return headers;
}
#Override
public String getBodyContentType() {
return "text/plain";
}
#Override
public byte[] getBody() throws AuthFailureError {
String httpPostBody = "ON";
return httpPostBody.getBytes();
}
};
RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
myStringRequest.setShouldCache(false);
MyRequestQueue.add(myStringRequest);
The body is overriden by getBody() and the specified header with getHeaders().

Set custom headers to all volley requests

Overriding getHeaders() works to add customs headers if necessary to the requests.
But what if X header is always needed to be set? for example an static auth token.
JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
setFollowButton(item);
}
}, null){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", "Token XXXXXXXXXXXX");
return headers;
}
};
Application.getInstance().addToRequestQueue(req);
Can be the header added to the request sent to the addToRequestQueue method instead overwriting it every time I write a request?
I believe the best way is extend the HttpStack sub-class which you choose to use, then intercepting the performRequest() method, put your global headers inside it.
public class MyHurlStack extends HurlStack {
#Override
public HttpResponse performRequest(
Request<?> request, Map<String, String> additionalHeaders)
throws IOException, AuthFailureError {
Map<String, String> headers = request.getHeaders();
// put your global headers
headers.put("Via", "netroid");
headers.put("Accept-Charset", "UTF-8");
headers.put("Origin", "http://netroid.cn/");
return super.performRequest(request, additionalHeaders);
}
}
public class MyHttpClientStack extends HttpClientStack {
public MyHttpClientStack(HttpClient client) {
super(client);
}
#Override
protected void onPrepareRequest(HttpUriRequest request) throws IOException {
// put your global headers
request.setHeader("Via", "netroid");
request.setHeader("Accept-Charset", "UTF-8");
request.setHeader("Origin", "http://netroid.cn/");
super.onPrepareRequest(request);
}
}
when RequestQueue initializing, use the customize HttpStack instead of.
if (stack == null) {
if (Build.VERSION.SDK_INT >= 9) {
stack = new HurlStack();
} else {
stack = new MyHttpClientStack(AndroidHttpClient.newInstance(userAgent));
}
}
Network network = new BasicNetwork(stack);
After a long search on how to add custom headers on each request with the volley android library,
I used HurlStack as bellow, hope it helps someone.
private static class MyHurl extends HurlStack{
#Override
public HttpResponse executeRequest(Request<?> request, Map<String, String> additionalHeaders){
Map<String, String> headers = new HashMap<>(additionalHeaders);
headers.put("authKey","myauthkey");
try {
return super.executeRequest(request, headers);
} catch (IOException e) {
} catch (AuthFailureError authFailureError) {
}
return null;
}
}

Categories