Why is API HTTP response 406 despite not passing accept header? - java

My API is calling some other service with URL
https://idgenvip.qa.ch3.s.com/IDGen/services/id/generate?idType=GIFT_REGISTRY_ID
and this service is returning me HTTP response code 406
which is not acceptable.
UtilHelper:691 - Exception occurred while generating id : Server
returned HTTP response code: 406 for URL:
https://idgenvip.qa.ch3.s.com/IDGen/services/id/generate?idType=GIFT_REGISTRY_ID
I'm not passing accept header in my request. What could be the other reason I'm getting this?

To be frank with you, a 406 response could be returned for any reason ... or no reason at all.
According to the HTTP 1.1 specification (Section 6.5.6) it should be returned is the one of these headers is requesting output in a representation that the server cannot provide:
Accept
Accept-Charset
Accept-Encoding
Accept-Language
If the server implementation is following the spec, the response body should list the representations that it can provide. (Look at the response body to see if it is saying anything.)
What else could it be?
It could conceivably be that the server is telling you that you need to provide an "accept" header.
It could conceivably be that the server is giving a deliberately misleading response, because it thinks you are abusing the API.
But I'm really guessing. As I said at the beginning ... it could be anything.
My advice would be to read the API documentation carefully, and ask the people who run the server what you are doing wring.

In my case when I checked the code, The accept header was hard coded in the code itself.
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");
connection.setRequestProperty("Content-Type", "application/json");
So when I removed/commented out the code the service stopped throwing 406. :-)

Related

Android (Java/Kotlin) - Http error 400 - Bad Request and the request have only header without body

everyone!
I've been building and app that consumes an API from the company where I work. When I perform a request (GET) with URL connection (through HttpURlConnection) with header (encoding, authorization and etc.) AND a body (as a JSON, using Content-Type = "application/json") the response code is 200 and the connection works pretty good, but and I use the same header in another request BUT WITHOUT a content, I get a Bad Request.
I already tried setting the doOutout = false, but It doesn't work.
I think that everything is OK with the URL and the header because I performed the request by Postman and I got the response.
Here is the way I'm creating the connection and connecting:
val uri = Uri.parse("Base URL").buildUpon().appendPath(path).build() val url = URL(uri.toString()) val connection = url.openConnection() as HttpURLConnection connection.apply {
addRequestProperty("Charset", Charsets.UTF_8.displayName())
addRequestProperty("Authorization", "Basic $token")
addRequestProperty("X-Serial", 5036.toString())
requestMethod = "GET"
connectTimeout = 0
readTimeout = 0
doOutput = false
if (responseCode != HTTP_OK) throws Exception("Erro")
}
Bad Request suggest that it's an issue with the way your request is formed.
It is likely a problem with one of the request headers that you are setting. Have a look at the accepted request headers here.
Charset should potentially be named Accept-Charset, and I haven't seen any examples of X-Serial being used.
Here is an example of setting up a GET request using HttpUrlConnection. You could try removing all headers apart from Authorization and setting the request method to GET, like in this example.
I found out what was the problem: Me!
The $token value was generate with the flag DEFAULT. After I realized that, I putted the flag NO_WRAP and my request worked.
My bad! But thanks for all support!

RESTFUL jetty service returning 403 error java

I am facing this HTTP 403 Forbidden response from a https REST service when I am trying to call it from my java code. Can you kindly let me know if I am missing something here?
Please note that the server returns the expected data when I trigger the request from any browser / SOAPUI/ Chrome Postman clients.
2 peer certificates are used - as shown in the ssl info from soapui after the request is sent.
The code snippet is attached. [The headers I set in the code are taken from the request header I found from the successful requests]
HttpsURLConnection connection = (HttpsURLConnection)new URL("https://server address").openConnection();
connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
connection.setRequestProperty("Accept-Encoding","gzip, deflate, br");
connection.setRequestProperty("User-Agent", "Apache-HttpClient/4.1.1");
connection.addRequestProperty("Connection", "Keep-Alive");
connection.addRequestProperty("Cache-Control","no-cache");
connection.setRequestMethod("GET");
connection.connect();
System.out.println("Response Code : " + connection.getResponseCode()+" "+connection.getResponseMessage());
Response Code : 403 Forbidden
Can you please check the Server URL if it is in the Java Acceptable format?
Sometimes java need escape characters to recognize strings correctly.
This question: What are all the escape characters? , can help you to check if you are using any of those characters. Also check if the conversion in the function is done properly.
Also, if you have more complex URL, consider to use java.net.URL .
Finally, check the user agent parameter Setting user agent of a java URLConnection .
Thanks for your response. The issue is with session cookie to be used for the connection. We are able to connect and get the response back with response code HTTP 200 once the cookie with JSESSIONID is passed as a header. Thanks again.

Cross Origin Resource sharing issue even when all the CORS headers are present

even though i have appended my service response with following provided CORS Headers :
resp.setContentType("application/json");
resp.addHeader("Access-Control-Allow-Origin", "*");
resp.addHeader("Access-Control-Allow-Credentials", "true");
resp.addHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
resp.addHeader("Access-Control-Allow-Headers", "Origin,accept,content-type");
resp.flushBuffer();
i am still getting below error in the console while trying to access some of the POST web methods in the service through my AngularJS frontend.
XMLHttpRequest cannot load http://192.***.*.***:8080/abc/def/search/vehicleManufacturer. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.***.*.***:8085' is therefore not allowed access.
However within the same class, some POST methods without any payloads are responding perfectly. Any suggestions ?
EDIT--------->
Below is my AngularJS client screen code for calling the web method:-
getVehicleModel : function(searchData,$scope){
$http({
method:'POST',
url:'http://192.169.*.***:8085/abc/def/search/vehicleModel',
dataType:'jsonp',
data:searchData
}).
success(function(data){
console.log("vehicle model")
$scope.vehicleModel = data.Response;
});
},
I think the problem here is Preflighted Requests in CORS.
From the Mozilla docs,
Unlike simple requests (discussed above), "preflighted" requests first
send an HTTP request by the OPTIONS method to the resource on the
other domain, in order to determine whether the actual request is safe
to send. Cross-site requests are preflighted like this since they may
have implications to user data. In particular, a request is
preflighted if:
It uses methods other than GET, HEAD or POST. Also, if POST is used to send request data with a Content-Type other than
application/x-www-form-urlencoded,
multipart/form-data
text/plain
e.g. if the POST request sends an XML payload to the server using application/xml or text/xml, then the request is preflighted.
It sets custom headers in the request (e.g. the request uses a header such as X-PINGOTHER)
As explained above, even though you're making a simple POST request, the Content-Type in your request is application/json which is different from the 3 types mentioned above, so it's considered as a Preflight request and an OPTIONS request is fired before your actual POST request.
You can solve this by implementing doOptions in your servlet, just add the headers there and it will work :)
The preflight (OPTIONS) is occurring due to the fact that you are sending a cross-origin ajax request AND specifying an Authorization header with this GET request.
Also (this is not causing an issue) I would suggest removing the contentType option. This doesn't make sense in the context of a GET request. A GET request should not have any content. All data should be included in the query string or, possibly, headers.
The Authorization header will not be sent with the OPTIONS. You must acknowledge it server-side, and then the browser will send the underlying GET. Read more about CORS at https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS .

Get only the response code not the full source of a url

I have an URL and i want only to check the response code of the page and not the complete page source as fetching the the complete page source is quite slow. what is right way to go ?
does getResponseCode() in HttpUrlConnection feches the complete page source or only the header ?
Straight from the docs, HttpUrlConnection#getResponseCode()
Gets the status code from an HTTP response message. For example, in the case of the following status lines:
HTTP/1.0 200 OK
HTTP/1.0 401 Unauthorized
It will return 200 and 401 respectively. Returns -1 if no code can be discerned from the response (i.e., the response is not valid HTTP).
Depends what you're motivation is in making the request. If the request is normally just a GET request for a resource and doesn't have any side effects.
You can perform a HTTP HEAD request instead, which if implemented correctly should get you the same status codes but not the body. (i.e. setRequestMethod(HEAD))
Here method may be PostMethod or GetMethod
you can get status code from an HTTP response message by getStatusCode()
example:-
int statuscode=method.getStatusCode();

Does the server send response only when its HTTP 200?

im writing a java application that sends a post request to a server and expect a json from the server. Now when i need to get the response from the server do i only need to get it from the inputStream when the http code is 200 (HTTP OK) or is there any other cases ? , example :
//...
if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
// only here try to get the response
}
//...
It depends on how the server is implemented. Check the API, if the server has one. If it's internal, ask your server guy.
Generally speaking, if your response code is either 2xx or 3xx, I would check the response anyway...
If the server your communicating with is following the spec then either 200 or 201 responses are valid to contain an entity. A 204 response is successful but has no data in the response.
See section 9.5 here: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.5 for details of acceptable responses to a POST. Extract below:
The action performed by the POST method might not result in a resource
that can be identified by a URI. In this case, either 200 (OK) or 204
(No Content) is the appropriate response status, depending on whether
or not the response includes an entity that describes the result.
If a resource has been created on the origin server, the response
SHOULD be 201 (Created) and contain an entity which describes the
status of the request and refers to the new resource, and a Location
header (see section 14.30).
There are three things to consider:
All 2xx codes denote success of some sort. But depending on the exact code, your reading code might be different. (204 for example means success but no content.)
There are redirecting codes (3xx). These are usually automatically followed by the http client library but you can also set them not to, in which case you need to have custom code that handles these cases.
There can be valuable information returned in the stream even if you get a code that denotes an error. Whether you want to process it depends on your exact needs.

Categories

Resources