Volley, BasicNetwork.performRequest: Unexpected response code 405, while making StringRequest - android

Using Volley, I POST StringRequest and i am getting error when i am accessing the url, as it is
https://www.google.com/?gfe_rd=cr&ei=vX8jVdTvOsOq8weigYHICA&gws_rd=cr&fg=1
But when is use http instead of https above, it won't give error and working well.
cookie and client code is below,
DefaultHttpClient client_R = new DefaultHttpClient();
RequestQueue queue_R = Volley.newRequestQueue(this, new HttpClientStack(client_R));
CookieStore store_R = client_R.getCookieStore();
Cookie cookie_R = new BasicClientCookie("Example_Cookie", "80");
store_R.addCookie(cookie_R);
below is logcat output,
[199] BasicNetwork.performRequest: Unexpected response code 405 for https://www.google.com/?gfe_rd=cr&ei=TX4jVcChFaTj8wehzoCgCw&gws_rd=cr&fg=1
Why it is giving error ? With some URLs having https, it is working instead.

The problem is that you are using a POST api request for a GET request.
In your StringRequest Method use GET instead of POST.
StringRequest sr = new StringRequest(Request.Method.GET, String url, Listener<String> listener, ErrorListener errorListener);

Do you use an SSL client for your https request.
Your 405 error code is a "Method Not Allowed" error: see more here
To use https, i use an OkHttpClient with a TrustManager.

Related

Android Volley EOFException

I have a simple app that uses volley like this:
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("VolleyController", "Received volley response: " + response);
callback.onCallback(OperationOutcome.SUCCESS, response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// This is null.
NetworkResponse response = error.networkResponse;
Log.e("VolleyManager", "Received error response from volley: ", error );
callback.onCallback(OperationOutcome.FAILURE, null);
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
This is the exception I get:
Received error response from volley: com.android.volley.NoConnectionError: java.io.EOFException
at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:151)
at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:112)
Caused by: java.io.EOFException
at com.android.okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:98)
at com.android.okhttp.internal.http.HttpConnection.readResponse(HttpConnection.java:202)
at com.android.okhttp.internal.http.HttpTransport.readResponseHeaders(HttpTransport.java:119)
at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:798)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:405)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:349)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:517)
at com.android.volley.toolbox.HurlStack.performRequest(HurlStack.java:110)
at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:96)
at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:112) 
I've found some other answers about this online but they didn't solve it. The request is not getting to the server.
Thank you very much.
EDIT
I have both the permission on the manifest:
<uses-permission android:name="android.permission.INTERNET" />
and Internet is working fine on the device.
Do you have your internet enabled on your device?
Did you set the INTERNET permission in your manifest?
EDIT:
Check your if your URL is correct.
The problem was due to the fact that the request I was sending was empty. I thought that Volley would convert it to the correct JSON representation({}) by itself. Instead, I think the request was just a null and this caused the exception. To fix this, I've changed the StringRequest in a JSONObjectRequest. This has a constructor which takes as an input a JSONObject like this:
// This will instantiate an empty JSON request with the correct format.
new JSONObject("{}");
I still don't get why Volley doesn't do by itself and I'd like to understand just out of curiosity. Anyway, after this, I've decided to switch to Retrofit which is much more performant and simpler to set up.
Thank you everybody for your help!

404 error with POST and OkHttp3

I'm having an issue posting data to the Challonge API with OkHttp3 on Android... This is the jist of my code:
OkHttpClient client = new OkHttpClient();
HttpUrl.Builder urlBuilder = new HttpUrl.Builder();
urlBuilder = HttpUrl.parse("https://api.challonge.com/v1/tournaments/"+EVENT_ID+".json")
.newBuilder();
RequestBody postBody = new FormBody.Builder()
.add("_method", "post")
.add("api_key", API_KEY)
.add("participant[name]", name.getText().toString())
.add("participant[misc]", forum_id.getText().toString())
.build();
Request request = new Request.Builder()
.url(urlBuilder.build().toString())
.post(postBody)
.build();
Response response = client.newCall(request).execute();
No matter what I do, the resulting reponse is a 404 page.
If I do a GET response to the same URL, I get a proper response. However, the moment I add .post(postBody) to the request, its immediately 404s.
The documentation for the Challonge API is here:
http://api.challonge.com/v1/documents/participants/create
It looks to me like you're just using the wrong URL. The URL you've got there, "https://api.challonge.com/v1/tournaments/"+EVENT_ID+".json", is the URL for retrieving a single tournament, as seen here. This link was meant to receive GET requests.
According to the link you provided, you should alter your code to POST to https://api.challonge.com/v1/tournaments/"+EVENT_ID+"/participants.json

Correct syntax for adding parameters to get() and post() request using okhttp in Android

What I want to achieve ?
I am trying to send two parameters in my Server URL using OkHttp through both get and post bcoz i want to know the syntax for both the methods.
What I had Tried ?
I have searched SO for questions on OkHttp but those had not solved my IllegalArgumentException.
I have seen below links :
Add query params to a GET request in okhttp in Android
and this
How to add parameters to api (http post) using okhttp library in Android
and
How to add query parameters to a HTTP GET request by OkHttp?
Exception from code 2:
Code I had used till now :
1)GET
urls = chain.request().httpUrl() <-- NullPointerException Line
.newBuilder()
.scheme("http")
.host(SERVER_IP)
.addQueryParameter("from", valueFrom)
.addQueryParameter("to",valueTo)
.build();
request = chain.request().newBuilder().url(urls).build();
response = chain.proceed(request);
2)GET
urls =new HttpUrl.Builder()
.host(SERVER_IP) <--- IllegalArgumentException line
.addQueryParameter("from", valueFrom)
.addQueryParameter("to", valueTo)
.build();
request = new Request.Builder().url(urls).build();
response = client.newCall(request).execute();
3)POST
body = new
MultipartBuilder().type(MultipartBuilder.FORM).addFormDataPart("from",
valueFrom).addFormDataPart("to",valueTo).build();
Log.i("Body data",""+body.toString());
request = new Request.Builder().url(params[0]).post(body).build();
Log.i("Request data",""+request.toString());
response = client.newCall(request).execute();
4)POST
body = new FormEncodingBuilder().add("from", valueFrom).add("to",
valueTo).build();
Log.i("Body data",""+body.toString());
request = new Request.Builder().url(params[0]).post(body).build();
Log.i("Request data",""+request.toString());
response = client.newCall(request).execute();
build.gradle
dependencies
{
compile files('libs/okhttp-2.5.0.jar')
compile files('libs/okio-1.6.0.jar')
}
Thanks In Advance...
Edit :
The above code for POST request is working fine now
But for GET request I still have no solution.
Just set your GET parameter extend your URL:
RequestBody body = new FormEncodingBuilder()
.add("requestParamName", requestParameter.getRequestParams())
.build();
Request request = new Request.Builder()
.url("https://www.test.com/serviceTest?parama=abc&paramb=123")
.post(body)
.build();

How send multipart/fom-data with Volley and get a response in a JSON Object?

I have a functionnal Android app send request with Volley and get response in JsonObject. Now, I need to include an image in my request and I don't have any idea how I can do that, and still receive my response in a JsonObject.
Thank you for helping.
Fabien.
JsonMultipartRequest<Upload> request = new JsonMultipartRequest<Upload>(Method.POST, apiUrl, mListener, mErrorListener);
request.addFile("photo", image_path);
RequestQueue mRequestQueue = Volley.newRequestQueue(getApplicationContext());
mRequestQueue.addRequest(request);
mRequestQueue.start();
JsonMulitpartRequest is extended class of MultipartRequest where Override the below method to make it JSON object parseNetworkResponse
This is using library VolleyPlus

sending json object to HTTP server in android

I am sending a JSON object to a HTTP Server by using the following code.
The main thing is that I have to send Boolean values also.
public void getServerData() throws JSONException, ClientProtocolException, IOException {
ArrayList<String> stringData = new ArrayList<String>();
DefaultHttpClient httpClient = new DefaultHttpClient();
ResponseHandler <String> resonseHandler = new BasicResponseHandler();
HttpPost postMethod = new HttpPost("http://consulting.for-the.biz/TicketMasterDev/TicketService.svc/SaveCustomer");
JSONObject json = new JSONObject();
json.put("AlertEmail",true);
json.put("APIKey","abc123456789");
json.put("Id",0);
json.put("Phone",number.getText().toString());
json.put("Name",name.getText().toString());
json.put("Email",email.getText().toString());
json.put("AlertPhone",false);
postMethod.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
String response = httpClient.execute(postMethod,resonseHandler);
Log.e("response :", response);
}
but its showing the exception in the line
String response = httpClient.execute(postMethod,resonseHandler);
as
org.apache.http.client.HttpResponseException: Bad Request
can any one help me.
The Bad Request is the server saying that it doesn't like something in your POST.
The only obvious problem that I can see is that you're not telling the server that you're sending it JSON, so you may need to set a Content-Type header to indicate that the body is application/json:
postMethod.setHeader( "Content-Type", "application/json" );
If that doesn't work, you may need to look at the server logs to see why it doesn't like your POST.
If you don't have direct access to the server logs, then you need to liaise with the owner of the server to try and debug things. It could be that the format of your JSON is slightly wrong, there's a required field missing, or some other such problem.
If you can't get access use to the owner of the server, the you could try using a packet sniffer, such as WireShark, to capture packets both from your app, and from a successful POST and compare the two to try and work out what is different. This can be a little bit like finding a needle in a haystack though, particularly for large bodies.
If you can't get an example of a successful POST, then you're pretty well stuffed, as you have no point of reference.
This may be non-technical, but
String response = httpClient.execute(postMethod,-->resonseHandler);
There is a spelling mistake in variable name here, use responseHandler(defined above)

Categories

Resources