Problem connecting spotify APIS using StringRequest - android

I'm trying to connect my android app to Spotify APIS.
Now I'm able to login, and play some random music with URL songs. My problem is I'm not able to connect using GET. And my only one response is:
E/Volley: [7721] BasicNetwork.performRequest: Unexpected response code 401 for
StringRequest stringRequest = new StringRequest(Request.Method.GET, URLline,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
parseData(response);
System.out.println("respuesta: " + response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("Accept", "application/json");
params.put("Content-Type", "application/json");
params.put("Authorization", "Bearer BQCljGDNl4xBRbSnJgl8O8tZU-OUIGGpBFsYZTD_QxcrHI-JN8-cFbfiewHTmSIlzMMuvRaX5lsPtDFwFsx_pNq37DEH8jll8sd9jXs6gPXGGTON0LOlzbzPXhAVz6mG_Ta-6BakiVo5C-MAjVL8UC9r9Hl8xIR_en9-tmpfCTKccEKI");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);

I think the problem is that you are sending the headers as GET parameters, you should override getHeaders().
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("xxx", "xxx");
return params;
}

Related

getHeaders Override method not being added to request

I'm trying to do a simple GET request in Android via Volley. However when I debug it the override method(s) are only called AFTER the request has been added to the queue. So my request thinks the headers object is empty and fails on the backend check. How can I make the request consume my headers before being sent to the backend?? I've looked at examples everywhere and I can't figure out why mine doesn't work. Please help!
private void getHello(){
String helloUrl = "https://...";
final String basicAuth = "Basic " + Base64.encodeToString("testUser:somePassword".getBytes(), Base64.NO_WRAP);
StringRequest stringRequest = new StringRequest(Request.Method.GET, helloUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("Hello Response: ",response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Hello Response Error: ",error.toString());
}
}){
#Override
public Map<String,String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
params.put("X-FXF-clientid", "123");
params.put("authorization", basicAuth);
return params;
}
};
queue.add(stringRequest);
}

Url working in Retrofit but not working in Volley

I have Url for Login. Its working and give response in Postman and Retrofit but not working with volley.
In volley its give error: com.android.volley.RedirectError
Why i geeting RedirectError. url working and give response in retrofit as well in postman.
Here is my Code:
public void Login(){
final String REGISTER_URL = "Here_My_Url";
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("onResponse", response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("eee123",error.toString());
Toast.makeText(getApplicationContext(), error.getMessage(),
Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("user_email", st_email);
params.put("password", st_pass);
Log.e("params", " " + params);
}
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
return headers;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(0, -1,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
stringRequest.setShouldCache(false);
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
}

Sending form data in volley post request

The postman response is this image:
This is the code i am using to send the data in the post request. Although i am getting a 400 response code from this.
StringRequest stringRequest = new StringRequest(Request.Method.POST,
API.ADD_PAYMENT,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
onBackPressed();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(AddPaymentActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("amount", "123");
params.put("description", "Not Paid");
params.put("customer", "1");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json; charset=UTF-8");
headers.put("Authorization", "token 0ee1248c5a84e8b1e36a8a15da48c0bb7580926c");
return headers;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(AddPaymentActivity.this);
requestQueue.add(stringRequest);
First of all why don't you use JsonObjectRequest instead of StringRequest when you're using application/json as your talking language with server? Second have you tried passing your parameters to the other request constructor like below?
Map<String, Object> params = new HashMap<>();
params.put("amount", 123);
params.put("description", "Not Paid");
params.put("customer", 1);
JsonObjectRequest jor = new JsonObjectRequest(Request.Method.POST, API.ADD_PAYMENT, new JSONObject(params), new Response.Listener<JSONObject>() {
...
Passing your headers are essential so the rest of you code remains as it is.

BasicNetwork.performRequest - Unexpected response code 400 (POST)

When I am trying to fetch data through rest api using Volley StringRequest or JsonObjectRequest. I always get 400 error. Its working fine with the postman. Http request method is POST, Content-Type is application/x-www-form-urlencoded. I have also checked my parameter spelling and it looks fine to me. I have tried with both StringRequest and JsonObjectRequest, result is E/Volley: [10283] BasicNetwork.performRequest: Unexpected response code 400. Below is my code. I have attached a screenshot.
Here is the new screenshot
StringRequest stringRequest = new StringRequest(Request.Method.POST, AppConfig.URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
viewHelper.hideDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, error.toString());
viewHelper.hideDialog();
}
}){
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("grant_type", "password");
params.put("username", email);
params.put("password", password);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
#Override
public String getBodyContentType(){
return "application/x-www-form-urlencoded";
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
AppController.getInstance().addToRequestQueue(stringRequest, "Authenticating User");
I have alos tried with volley JSONObjectRequest
Map<String, String> params = new HashMap<String, String>();
params.put("grant_type", "password");
params.put("username", email);
params.put("password", password);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, AppConfig.URL_LOGIN, new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/x-www-form-urlencoded");
return headers;
}
};
Can anyone please help me in fixing this issue.
Below is the working example of POST request using Volley library.
Add this to your build.gradle (Module:app) -
compile 'com.mcxiaoke.volley:library:1.0.19'
StringRequest stringRequest = new StringRequest(Request.Method.POST, AppConfig.URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
progressDialog.dismiss();
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(response);
if(jsonObject.has("success")){
if(jsonObject.getBoolean("success") == true){
JSONObject userObject = new JSONObject(jsonObject.getString("user"));
Map<String, String> loginDetails = new HashMap<String, String>();
loginDetails.put(KEY_IS_LOGGED_IN, "true");
loginDetails.put(ACCESS_TOKEN, jsonObject.getString(ACCESS_TOKEN));
loginDetails.put(USERID, userObject.getString(USERID));
loginDetails.put(FIRSTNAME, userObject.getString(FIRSTNAME));
loginDetails.put(LASTNAME, userObject.getString(LASTNAME));
loginDetails.put(EMAIL, userObject.getString(EMAIL));
session = new SessionManager(_myActivity);
session.setLogin(loginDetails);
Intent intent = new Intent(LoginActivity.this, SearchActivity.class);
intent.putExtra("FROM_ACTIVITY", "LoginActivity");
startActivity(intent);
LoginActivity.this.finish();
}else{
btnLogin.setClickable(true);
btnLogin.setEnabled(true);
Toast.makeText(getApplicationContext(), "Username or Password does not matched!", Toast.LENGTH_LONG).show();
}
}
} catch (JSONException e) {
btnLogin.setClickable(true);
btnLogin.setEnabled(true);
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Something went wrong, Please try agian", Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, error.toString());
progressDialog.dismiss();
btnLogin.setClickable(true);
btnLogin.setEnabled(true);
}
}){
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("grant_type", "password");
params.put("username", email);
params.put("password", password);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
#Override
public String getBodyContentType(){
return "application/x-www-form-urlencoded";
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
RequestQueue mRequestQueue = Volley.newRequestQueue(getApplicationContext());
mRequestQueue.add(stringRequest);
Please comment if anyone faced issue with above code.
Thanks to everyone who tried to help me.
A 400 means bad request the data sent by the you to the server didn't follow the rules.So check your parameter or spelling of these parameter which is required by server.
So check those try again hope it work for you :)
Unexpected response code 400 means Bad Reuest.
This Response is caused by sending wrong parameters with the URL.
To solve:
Check every parameter with spelling.
Make sure if response is obtained in string or in object. stringRequest or JSONObjectReuest
Also check Content-type
use this as Content-type
#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");
return headers;
}
For JsonObjectReuest use:
HashMap<String, String> params = new HashMap<String, String>();
params.put("name", "BLah");
JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.d("Response:", response.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error: ", error.getMessage());
}
});

Post Method using Volley not working

Hi i am using Volley for my login page. I need to pass data like this manner
{
userID : '-988682425884628921',
email :'aditya#vyas.com',
passwd : '123ss'
}
I am using POST Method to send data,I already check in DHC, The Api is working fine in DHC and I am getting JSON Response, But when i try with Volley i am not able to get response. and not even any error in my logcat.
JAVA code
RequestQueue mVolleyQueue = Volley.newRequestQueue(this);
CustomRequest req = new CustomRequest(Request.Method.POST,url,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.v("tag","login response " + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.v("tag","login error response " + error.getMessage());
}
}){
#Override
public Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("userID", "-988682425884628921");
params.put("email", "aditya#vyas.com");
params.put("passwd", "123ss");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
mVolleyQueue.add(req);
Error
05-28 09:20:14.696 2450-2468/com.android.msahakyan.expandablenavigationdrawer E/tag﹕ parseNetworkError is ! null
05-28 09:20:14.697 2450-2468/com.android.msahakyan.expandablenavigationdrawer E/tag﹕ parseNetworkError status code : 400
05-28 09:20:14.697 2450-2468/com.android.msahakyan.expandablenavigationdrawer E/tag﹕ parseNetworkError message : <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Bad Request - Invalid Header</h2>
<hr><p>HTTP Error 400. The request has an invalid header name.</p>
</BODY></HTML>
}
Solved your problem. Just used JsonArrayRequest and passed parameters in JsonObject form:
Map<String, String> params = new HashMap<String, String>();
params.put("userID", "userid");
params.put("email","email");
params.put("passwd", "password");
JsonArrayRequest request = new JsonArrayRequest(Request.Method.POST, "url", new JSONObject(params),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
System.out.println("response -->> " + response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("change Pass response -->> " + error.toString());
}
});
request.setRetryPolicy(new
DefaultRetryPolicy(60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Volley.newRequestQueue(activity).add(request);
No need of overriding getParams() or getHeaders().
Problem : 1
You were getting response code 500 because the server was accepting the params as JsonObject and we are trying to feed String.
Problem : 2
You were using JsonObjectRequet but the response from the server was in JsonArray so you need to use JsonArrayRequest to accept the response in JsonArray
Try and let me know this helps or not :)
I had a similar problem. I had overwritten the Content-Type in the getHeaders Method:
headers.put("Content-Type", "application/json; charset=UTF-8");
but Volley itself added a Content-Type parameter, so there were two of those parameters. Delete the line had solved my Problem.
You need to override protected Map<String, String> getParams() to pass parameters in POST.
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, params,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Login Response", response.toString());
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error.getStackTrace());
VolleyLog.d("ErrorVolley", "Error: " + error.getStackTrace());
hidepDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("userID", "2"));
params.put("email","aa#a.kl");
params.put("passwd", "ddddd");
return params;
}
};
Beware of content-type header. Volley handles it differently from other headers and it's not shown in Map<> Headers. Instead of overriding getHeaders() method to set content-type, you should override getBodyContentType() like this:
#Override
public String getBodyContentType()
{
return "application/json; charset=utf-8";
}
i have same problem use this :
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(LoginActivity.this, response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
public Map<String, String> getParams() {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
headers.put("UN", UserName);
headers.put("PW", PassWord);
return headers;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
Just need to add headers.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); to parms
good luck.

Categories

Resources