I am making a Video Player App and want to use 'open subtitles api' to download the subtitles from within the app same like the 'VLC media player' does. When triggering the download API, Volley is giving this error when giving a POST request with three headers and one parameters. The API is working properly and it is getting triggered when I run my app. I have tried and tested on postman and it is working fine and giving this response however I am not getting this response in android app instead "com.android.volley.ClientError" and I am stuck here.
This is my code:
public void sendDownloadRequest() {
StringRequest downloadRequest = new StringRequest(Request.Method.POST, downloadurl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(context, "Response: " + response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Toast.makeText(context, "Error from Download: " + error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Nullable
#Override
protected Map<String, String> getParams() {
Map<String, String> bodyParams = new HashMap<>();
bodyParams.put("file_name", "batman");
return bodyParams;
}
#Nullable
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headerParams = new HashMap<>();
headerParams.put("Authorization", "My Auth Key");
headerParams.put("Api-Key", "My Api Key");
headerParams.put("Content-Type", "application/x-www-form-urlencoded");
return headerParams;
}
};
requestQueue.add(downloadRequest);
This is the request body of postman
I thought that it could be the error of the parameters but I am already giving the right params
Any help would be appreciated.
Try overriding the getBodyContentType() as well,
...
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
protected Map<String, String> getParams() {
...
and remove the Content-Type header.
Related
I'm working with Mailchimp and I want to send an email address to my list, I have done this so far with Volley:
public void suscribeMailChamp(){
String listid = "listID";
String url = "https://us16.api.mailchimp.com/3.0/lists/" + listid + "/members/";
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest sr = new StringRequest(Request.Method.POST,url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//
Toast.makeText(MainActivity.this , "success" , Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this , error.toString() , Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("email_address","testmailchimp#gmail.com");
params.put("status","unsubscribed");
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");
params.put("Authorization" , "apikey <here my api key>");
return params;
}
};
queue.add(sr);
}
but I get error 400:
Unexpected response code 400 for
https://us16.api.mailchimp.com/3.0/lists/b9a5943047/members/
Here is a link for troubleshooting but I can't get the error:
http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/
Did you check the error in the link? It says
{
"type":"http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/",
"title":"API Key Missing",
"status":401,
"detail":"Your request did not include an API key.",
"instance":"924c81cc-90e9-498d-b0fd-c7b54cba207f"
}
which means you are not (or correctly) sending the API key for mail chimp in the request. Just add the mailChimp API key in the params for Volley request
So the way you would send your API key is this
params.put("Authorization", "Basic "+Base64.encodeToString(("apikey:"+apiKey).getBytes("UTF-8"),Base64.DEFAULT))
I got stuck at this too. Mailchimp documentation is very poor.
I found the solution from github
Just send 'Authorization': 'apikey myapikey' in your header
I am trying to upload an image to my Imgur account using Volley StringRequest. I am not sure how to handle the response so what happens is it keeps re uploading since it hasnt received a response from Imgur. The image ends up being uploaded a couple of times until the TimeoutError is thrown. How can I ensure this does not happen as I cannot detect the response being returned from the Imgur server?Here is the method I am using to upload the image after converting it to Base64:
public void uploadImage(View view) {
Log.i(TAG,"start upload");
StringRequest uploadRequest = new StringRequest(Request.Method.POST, AppConst.IMGUR_ADD_IMG, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "finished image upload");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, error.toString());
Log.e(TAG,"finish/error upload");
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Bearer " + token);
return headers;
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put(AppConst.IMGUR_TAG_IMAGE, encodeImage(selectedImg));
params.put(AppConst.IMGUR_TAG_TITLE, "title");
params.put(AppConst.IMGUR_TAG_NAME, String.valueOf(System.currentTimeMillis()));
return params;
}
};
AppController.getInstance().addToRequestQueue(uploadRequest);
}
Change the DefaultRetryPolicy on the Request to have a larger expiration time frame, since uploading an image can take a bit. Also, for the double upload, make sure to have max_retries set to 0.
new DefaultRetryPolicy(LONGER_TIMEOUT, 0, 0);
I am using volley to send web service request and volley response is SERVER ERROR (this site requires java script enabled). I tried POST and GET methods.
After some search on this issue I found these two questions..
Volley Server error (Requires javascript?) Android Development but there is no answer to solve this issue in 2 months
Disable Javascript on volley StringRequest but there is no answer to solve this issue in 6 months
No more questions and solution found. Can anyone tell the exact problem and solution with this issue.
Here is my code
public void postRequest(final JSONObject jsonParams,final Handler handler){
StringRequest stringRequest = new StringRequest(Request.Method.POST, AppConstants.ADMIN_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Message message = handler.obtainMessage();
message.obj = response;
handler.sendMessage(message);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Message message = handler.obtainMessage();
message.obj = error.toString();
Log.d("error",error.toString());
handler.sendMessage(message);
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
Iterator<String> iter = jsonParams.keys();
while (iter.hasNext()) {
try {
String key = iter.next();
String value = jsonParams.get(key)+"";
params.put(key,value);
} catch (JSONException e) {
// Something went wrong!
Message message = handler.obtainMessage();
message.obj = e.getMessage();
handler.sendMessage(message);
}
}
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers = new HashMap<String, String>();
return headers;
}
};
MyVolley.getInstance(context).getRequestQueue().add(stringRequest);
}
and web service code is
<?php if(true) { echo 'request arrived'; } ?>
There is a nice workaround suggested in this answer.
In Volley, you can override getHeaders() method to send the cookie with your HTTP request.
Code :
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
map.put("Cookie", "__test=YOUR COOKIE HERE; expires=Friday, January 1, 2038 at 5:25:55 AM; path=/");
return map;
}
i faced the same problem , and there is no direct solution for this
problem is:- some servers won't allow these type requests , they allow only web browsers
solution:-
Implement a webview in your app without any UI (if you are
expecting Json response).
Override onPageFinished inside setWebwiewclient().
get the page cookie by : String cookies = CookieManager.getInstance().getCookie(url);
after getting cookie pass the cookie in header of volley request
by key="cookie"
code reference:-
WebView webViewRequest=new WebView("your app context");
webViewRequest.getSettings().setJavaScriptEnabled(true);
webViewRequest.setWebViewClient(new WebViewClient());
webViewRequest.getSettings().setLoadWithOverviewMode(true);
webViewRequest.getSettings().setUseWideViewPort(true);
webViewRequest.getSettings().setSupportZoom(false);
webViewRequest.getSettings().setBuiltInZoomControls(false);
webViewRequest.getSettings().setDisplayZoomControls(false);
webViewRequest.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webViewRequest.requestFocusFromTouch();
webViewRequest.getSettings().setAppCacheEnabled(false);
webViewRequest.setScrollbarFadingEnabled(false);
webViewRequest.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
cookies = CookieManager.getInstance().getCookie(url);//here you will get cookie
Log.d(TAG, "onPageFinished: "+cookies);
StringRequest Request = new StringRequest(url, new
Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "onResponse: "+response.toString());
// your data from server
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
map.put("Cookie", cookies);
return map;
}
};
Mysingleton.getMinstance(DashboardActivity.context).addToRequestQue(Request);
}
});
webViewRequest.loadUrl("your url here");
}
I came across this error recently! Your code is totally fine but the problem lies with your web host. (Is it byethost)?
It has a bot detector running which does not let your Android volley request in.Unfortunately this cannot be disabled /turned off.
Try changing your web hosting service.
Hope this helpsâș
My partner made an API.
Then in the given link I'm trying to get the datas in JSON.
In postman it's working fine.
And in postman i just set the Authorization to No Auth and paste the link and its working.
In android its different.
I am receiving Error code 400.
But when i tried it in android studio it's not working.
String REVIEW_URL;
REVIEW_URL ="http://be0658e94af429e2150dd0a3dc1a199a:fdf2a81d6a88e86826b8f9530ea190bf#somesite.esy.es/api.php/reviews/12";
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
StringRequest request = new StringRequest(Request.Method.GET, REVIEW_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("RESPONSE:", response);
Toast.makeText(SignUp.this, response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> header = new HashMap<>();
return header;
}
};
requestQueue.add(request);
I am receiving this error.
01-09 01:19:24.828 9109-9210/com.toweelo E/Volley: [245] BasicNetwork.performRequest: Unexpected response code 401 for http://be0658e94af429e2150dd0a3dc1a199a:fdf2a81d6a88e86826b8f9530ea190bf#somesite.esy.es/api.php/reviews/12
Since you are using the GET method, check if REVIEW_URL value is really correct,
A 400 error means that the request was malformed. In other words, the
data stream sent by the client to the server didn't follow the rules.
I'm trying to use Volley library to communicate with my RESTful API.
I have to POST string in the body, when I'm asking for the bearer Token. String should look like this:
grant_type=password&username=Alice&password=password123
And header:
Content-Type: application/x-www-form-urlencoded
More info about WebApi Individual Accounts:
http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api
Unfortunately I can't figure out how can I solve it..
I'm trying something like this:
StringRequest req = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
VolleyLog.v("Response:%n %s", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("grant_type", "password");
params.put("username", "User0");
params.put("password", "Password0");
return params;
}
#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");
return headers;
}
};
I'm getting 400 Bad Request all the time.
I think that I'm actually sending request like this:
grant_type:password, username:User0, password:Password0
instead of:
grant_type=password&username=Alice&password=password123
I would be very grateful if anyone has any ideas or an advice..
To send a normal POST request (no JSON) with parameters like username and password, you'd usually override getParams() and pass a Map of parameters:
public void HttpPOSTRequestWithParameters() {
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://www.somewebsite.com/login.asp";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR","error => "+error.toString());
}
}
) {
// this is the relevant method
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("grant_type", "password");
// volley will escape this for you
params.put("randomFieldFilledWithAwkwardCharacters", "{{%stuffToBe Escaped/");
params.put("username", "Alice");
params.put("password", "password123");
return params;
}
};
queue.add(postRequest);
}
And to send an arbitary string as POST body data in a Volley StringRequest, you override getBody()
public void HttpPOSTRequestWithArbitaryStringBody() {
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://www.somewebsite.com/login.asp";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR","error => "+error.toString());
}
}
) {
// this is the relevant method
#Override
public byte[] getBody() throws AuthFailureError {
String httpPostBody="grant_type=password&username=Alice&password=password123";
// usually you'd have a field with some values you'd want to escape, you need to do it yourself if overriding getBody. here's how you do it
try {
httpPostBody=httpPostBody+"&randomFieldFilledWithAwkwardCharacters="+URLEncoder.encode("{{%stuffToBe Escaped/","UTF-8");
} catch (UnsupportedEncodingException exception) {
Log.e("ERROR", "exception", exception);
// return null and don't pass any POST string if you encounter encoding error
return null;
}
return httpPostBody.getBytes();
}
};
queue.add(postRequest);
}
As an aside, Volley documentation is non-existent and quality of StackOverflow answers is pretty bad. Can't believe an answer with an example like this wasn't here already.
First thing, I advise you to see exactly what you're sending by either printing to the log or using a network sniffer like wireshark or fiddler.
How about trying to put the params in the body? If you still want a StringRequest you'll need to extend it and override the getBody() method (similarly to JsonObjectRequest)
I know this is old, but I ran into this same problem and there is a much cleaner solution imo found here: How to send a POST request using volley with string body?