OData POST Response - java

I am giving request to OData POST in Json format and it's returning the same request to me.
POST URL= http://localhost:8085/MagicXpiOData/Odata_get.OData_1/Student_details
Body:
{"Division": "Nashik"}
Content-Type = application/json
Response:
{
"#odata.context": "$metadata#Student_details",
"Division": "Nashik"
}
Is this a correct response?
I think it should return a status code for success or not.

What you show above is the response body, which usually contains the OData.Context. Beside that you should find the HTTP Status Code in the header, which might be something like
HTTP/1.1 200 OK
HTTP/1.1 201 Created
and when you create a new entry also a location header.
Some examples that show typical requests and responses can be found in this Basic Tutorial
So generally your response looks ok. Maybe you can add the response header in your question, then we can see if everything is there what should be there.
When you send your request with a tool like Postman or Fiddler, you might by default only see the response body. To see the headers you need to switch to Headers, or Raw in Fiddler to see the full response (header and body).

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!

HttpClientErrorException 406 null is thrown in rest template spring mvc [duplicate]

In my Ruby on Rails application I tried to upload an image through the POSTMAN REST client in Base64 format. When I POST the image I am getting a 406 Not Acceptable Response. When I checked my database, the image was there and was successfully saved.
What is the reason for this error, is there anything I need to specify in my header?
My request:
URL --- http://localhost:3000/exercises.json
Header:
Content-Type - application/json
Raw data:
{
"exercise": {
"subbodypart_ids": [
"1",
"2"
],
"name": "Exercise14"
},
"image_file_name": "Pressurebar Above.jpg",
"image":"******base64 Format*******"
}
Your operation did not fail.
Your backend service is saying that the response type it is returning is not provided in the Accept HTTP header in your Client request.
Ref: http://en.wikipedia.org/wiki/List_of_HTTP_header_fields
Find out the response (content type) returned by Service.
Provide this (content type) in your request Accept header.
http://en.wikipedia.org/wiki/HTTP_status_code -> 406
406 Not Acceptable
The resource identified by the request is only capable of generating response entities which have content characteristics not
acceptable according to the accept headers sent in the request.
406 happens when the server cannot respond with the accept-header specified in the request.
In your case it seems application/json for the response may not be acceptable to the server.
You mentioned you're using Ruby on Rails as a backend. You didn't post the code for the relevant method, but my guess is that it looks something like this:
def create
post = Post.create params[:post]
respond_to do |format|
format.json { render :json => post }
end
end
Change it to:
def create
post = Post.create params[:post])
render :json => post
end
And it will solve your problem. It worked for me :)
"Sometimes" this can mean that the server had an internal error, and wanted to respond with an error message (ex: 500 with JSON payload) but since the request headers didn't say it accepted JSON, it returns a 406 instead. Go figure. (in this case: spring boot webapp).
In which case, your operation did fail. But the failure message was obscured by another.
You can also receive a 406 response when invalid cookies are stored or referenced in the browser - for example, when running a Rails server in Dev mode locally.
If you happened to run two different projects on the same port, the browser might reference a cookie from a different localhost session.
This has happened to me...tripped me up for a minute. Looking in browser > Developer Mode > Network showed it.
const request = require('request');
const headers = {
'Accept': '*/*',
'User-Agent': 'request',
};
const options = {
url: "https://example.com/users/6",
headers: headers
};
request.get(options, (error, response, body) => {
console.log(response.body);
});
Changing header to Accept: */* resolved my issue and make sure you don't have any other Accept Header
In my case, I added:
Content-Type: application/x-www-form-urlencoded
solved my problem completely.
If you are using 'request.js' you might use the following:
var options = {
url: 'localhost',
method: 'GET',
headers:{
Accept: '*/*'
}
}
request(options, function (error, response, body) {
...
})
In my case for a API in .NET-Core, the api is set to work with XML (by default is set to response with JSON), so I add this annotation in my Controller :
[Produces("application/xml")]
public class MyController : ControllerBase {...}
Thank you for putting me on the path !
It could also be due to a firewall blocking the request. In my case the request payload contained string properties - "like %abc%" and ampersand symbol "&" - which caused the firewall to think it is a security risk (eg. a sql injection attack) and it blocked the request. Note here the request does not actually go to the server but is returned at the firewall level itself.
In my case, there were no application server logs generated so I knew that the request did not actually reach the server and was blocked before that. The logs that helped me were Web application firewall (WAF) logs.

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 .

How to send a JSON string with an HTTP request using in Java using HTTPClient

This is my first question. I love stackOverflow but I've always been a reader, not a writer. Now here goes nothing:
So I've seen a LOT of different questions like this, believe me, I looked... but none of them seemed to answer my question exactly. I'm designing a test harness to test an API, and it involves sending HTTP requests using HttpClient (in Java). For some of the requests, such as POST requests, a JSON string or an XML string must be sent with the request. (I'm only asking about JSON here, if anyone had the answer of how to do the XML as well, I'd love that, but I'll save it for another question.)
Anyways, I have the following code so far which seems like it SHOULD do what I want... but I'm getting 400 error. I'm going to assume that I've properly created an instance of an HttpClient and an HttpPost, applied appropriate headers, etc... the pertinent part is below:
JSONObject JSONpayload = new JSONObject();
JSONpayload.put("quantity", 1);
JSONpayload.put("sku", "21-53429");
String JSONstring = JSONpayload.toString();
System.out.println("JSON PAYLOAD BEING SENT: " + JSONstring);
request.setEntity(new StringEntity(JSONstring));
response = client.execute(request);
System.out.println("SERVER RESPONSE STRING: " + response.toString());
And I receive the following output:
JSON PAYLOAD BEING SENT: {"quantity":1,"sku":"21-53429"}
SERVER RESPONSE STR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J2aWNlL3N2Yy92MS4wL3N0b3Jlcy9UTVNVUy9jYXJ0cy85T1ZfQUFBQkdCZ0FBQUVfSVNBUUE0YzIvaXRlbXN0AAdTdG9yZUlEdAAMc3RvcmVzL1RNU1VTdAAKaW5wdXQtdHlwZXEAfgATeHEAfgAJeHg=,
X-MULE_ENCODING: UTF-8,
Content-Type: text/plain,
Transfer-Encoding: chunked]
Now, I know the basic things and I'm pretty sure I've taken care of them... like setting the headers Accept application/json, Content-Type application/json, etc..
Any advice would be greatly appreciated. I'm new to using HttpClient and I'm a little lost haha. Thanks guys!
The problem is that this server requires authentication and you're not providing it (or using invalid credentials). I can tell that because the response code was 401 (Unauthorized).
401: Similar to 403 Forbidden, but specifically for use when authentication
is required and has failed or has not yet been provided [...]
HTTPClient's home page has a lot of information regarding authentication. You can check how to do that here also check some code examples here.

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();

Categories

Resources