Volley Server error this site requires java script enabled - android

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â˜ș

Related

Volley POST Request: 'com.android.volley.ClientError'

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.

Can't access volley answer saved

I am using this method to access a post Volley request
...
responseVolley = "";
getProductFromDataBase("6130127000035");
Log.d("responseVolley", responseVolley);
...
And my getProductFromDataBase is looking like this
public void getProductFromDataBase(final String bareCode) {
mPreferences = getApplicationContext().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
this.mEditor = mPreferences.edit();
String url = Constants.URL_SELECT_PRODUCT + "?" + Constants.PARAM_PRODUCT_CODE_BARE + bareCode;
Log.d("URL", url);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response", response);
responseVolley = response;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("response", "EROOR");
}
}) {
protected HashMap<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
return (HashMap<String, String>) params;
}
};
RequestHandler.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
}
When I am trying to show responseVolley it doesn't even show something in the Logcat ( I've tried many other solutions like shared preferences ) but nothing worked
Am I doing something wrong ?
Using Volley, you should verify these points :
Check and recheck the url string, if you did not deploy your web app, you should use the IP address you used start your server (http://loaclhost:port_number for example).
If your web app is not deployed on the internet yet, your server and your android app must be in the same network (try to make a hotspot from your PC and connect from your device).
In order to see a result in your response, you should return a string for example from the function that route the asked url, i.e. you should have a function in your web app that you want to send data to a function that catch your url in demande, you should return a string in that function.
You should also verify the error log, use a different tag from the response log tag.
Some times you should give some retry time (in case of weak connection):
stringRequest.setRetryPolicy(new RetryPolicy() {
#Override
public int getCurrentTimeout() {
return 50000;
}
#Override
public int getCurrentRetryCount() {
return 50000;
}
#Override
public void retry(VolleyError error) throws VolleyError {
}
}
PS: In the code you provided you are sending nothing, you should put strings you want to send like this:
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("key", "value");
return params;
}
You should use callback method to do what you expect. With help of an interface, you can achieve what you actually want. If it doesn't work, let me know.
getProductFromDataBase("6130127000035");
OnResult onResult = new OnResult() {
#override
public void result(String responseVolley) {
Log.d("responseVolley", responseVolley);
}
};
Your getProductFromDataBase() method
interface OnResult {
void result(String responseVolley);
}
public void getProductFromDataBase(final String bareCode) {
mPreferences = getApplicationContext().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
this.mEditor = mPreferences.edit();
String url = Constants.URL_SELECT_PRODUCT + "?" + Constants.PARAM_PRODUCT_CODE_BARE + bareCode;
Log.d("URL", url);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response", response);
onResult.result(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("response", "EROOR");
}
}) {
protected HashMap<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
return (HashMap<String, String>) params;
}
};
RequestHandler.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
}

below is my code i want to send the image url to server not the complete image by using below code i am getting server 500 error in android studio

Is okhttp is good for this or do you have any code similar to this ping me
Posting Data To server By Get Method
public void sendingDataToServer(){
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("onResponseSuccess", response.toString() + "check");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("onResponseSuccess", error.toString() + "check");
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json; ");
headers.put("x-oc-Image-url", "Your Image Path Url");
try {
headers.putAll(super.getHeaders());
} catch (AuthFailureError authFailureError) {
authFailureError.printStackTrace();
}
return super.getHeaders();
}
};
Volley.newRequestQueue(mContext).add(stringRequest);
}
If Your Sending Only Url to server there are ways to send Image Url to server
1. Passing through Header
2. Passing through JsonObject
I Suspect their is not posting Image Url path in your code.
In Server Side 500 error means request parameter not receiving to server time you will get this error.

StringRequest with JSON body

I'm trying to send a request using Volley but I can't figure how to make it work.
I need to send a POST request with JSON encoded data as the body, but after hours of trying different things I still can't make it work.
This is my current code for the request:
User user = User.getUser(context);
String account = user.getUserAccount();
String degreeCode = user.getDegreeCode();
final JSONObject body = new JSONObject();
try {
body.put(NEWS_KEY, 0);
body.put(NEWS_DEGREE, degreeCode);
body.put(NEWS_COORDINATION, 0);
body.put(NEWS_DIVISION, 0);
body.put(NEWS_ACCOUNT, account);
} catch (JSONException e) {
e.printStackTrace();
}
StringRequest request = new StringRequest(Request.Method.POST, GET_NEWS, new Response.Listener<JSONObject>() {
#Override
public void onResponse(String response) {
Log.i(TAG, response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + getMessage(error, context));
Toast.makeText(context, getMessage(error, context), Toast.LENGTH_SHORT).show();
}
}) {
#Override
public byte[] getBody() throws AuthFailureError {
return body.toString().getBytes();
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type","application/json");
return headers;
}
};
queue.add(request);
But this code always returns "Bad request error"
Some things I've tried:
Override getParams() method instead of getBody(). (Didn't work)
Send a JSONObjectRequest with the body on the constructor. This one worked, but because my web service returns a String value I always get a ParseError. That's why I'm using StringRequest.
Any help is very much appreciated.
As already mentioned on njzk2's comment, the easiest way is to override getBodyContentType() instead. Overriding getHeaders() could probably work too, but you need to put all necessary headers, not only Content-Type, since you basically override the headers that the original method set.
Your code should look like this:
StringRequest request = new StringRequest(...) {
#Override
public byte[] getBody() throws AuthFailureError {
return body.toString().getBytes();
}
#Override
public String getBodyContentType() {
return "application/json";
}
};

Android Volley POST string in body

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?

Categories

Resources