I have a simple RESTLET Service which returns a JSON representation, as shown below:
#Override
#Post("json")
public Representation helloWorld() {
Representation representation = new JacksonRepresentation<Hello>(new Hello("Hello World"));
representation.setMediaType(MediaType.APPLICATION_JSON);
representation.
return representation;
}
When I query this using cURL I get the response as expected:
{"greeting":"Hello World"}
However I do not get a response when I use the browser or POSTMAN or indeed any other web REST client. I get the response 'Could not get any response' from POSTMAN.
The preview of the POSTMAN request is:
POST /testingrestlet/hello HTTP/1.1
Host: 127.0.0.1:6000
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 5141cd87-505c-e813-0045-3b7f4aa54144
I would at least have expected a REST client such as POSTMAN to work, or am I missing something?
Any help appreciated.
Regards
I think that you should use an header Accept for the content negotiation (conneg). Your request should be:
POST /testingrestlet/hello HTTP/1.1
Host: 127.0.0.1:6000
Content-Type: application/json
Accept: application/json
Cache-Control: no-cache
Postman-Token: 5141cd87-505c-e813-0045-3b7f4aa54144
As a matter of fact, since you specify the extension "json" in the annotation, Restlet expects that this header was sent with one of possible media types for JSON content. This hint is used to select the method for processing... You shouldn't have this problem if you remove the extension, as described below:
#Post
public Representation helloWorld() {
Representation representation
= new JacksonRepresentation<Hello>(new Hello("Hello World"));
representation.setMediaType(MediaType.APPLICATION_JSON);
(...)
return representation;
}
Hope it helps you,
Thierry
With help from Thierry's comments the issue was traced down to Google Chrome blocking requests to port 6000 as it considers them unsafe. The error was only visible in Chrome Debug mode where the ERR_UNSAFE_PORT error was reported. Changing to a higher port resolved the issue! Detail of this error can also be found here: https://superuser.com/questions/188006/how-to-fix-err-unsafe-port-error-on-chrome-when-browsing-to-unsafe-ports
Related
I am trying to test a web API using JMeter. The web server interacts between JMeter and a database. The server is supposed to take parameters from the JSON in HTTP POST requests and parse them into queries.
The code of the web server in the relevent controller looks like this:
[HttpPost]
[Route("my_awesome_route_path")]
public async Task<List<QueryResult>> invoice([FromBody]InvoiceInfo invoiceInfo)
{
query = string.Format("INSERT INTO my_awesome_table (`my`,`awesome`,`columns`) " +
"VALUES ({0},{1},{2});", invoiceinfo.awesomeparam1, ... ,invoiceinfo.awesomeparamn);
noRowsInserted = await db.Database.ExecuteSqlCommandAsync(query);
And In my JMeter HTTP request form I entered the correct path for the above controller function. I left the parameters and files upload tabs empty while filling the body data tab with the following:
${__FileToString(/my/awesome/file/path${__eval({awesome_json_file_name_with_no_dottxt_in_end_altough_it_has_it})}.txt,,)}
Running the server and with no body data does reach the function to a breakpoint I set. So I know the route path is fine. Adding the above code to the body data causes a 415 error - Unsupported Media Type. Here is the httpsample provided by an output file by JMeter:
<httpSample t="8023" it="0" lt="8023" ct="2" ts="1544434665189" s="false" lb="HTTP Request" rc="415" rm="Unsupported Media Type" tn="Thread Group 1-3" dt="text" by="382" sby="281" ng="1" na="1">
<responseHeader class="java.lang.String">HTTP/1.1 415 Unsupported Media Type
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: todays_awesome_date
Content-Length: 103
</responseHeader>
<requestHeader class="java.lang.String">Connection: keep-alive
Content-Length: 37
Content-Type: multipart/form-data; boundary=jBtzRzXGjCNVf_3UH8LfxguE6qR9_xH
Host: awesome_ip_add
User-Agent: Apache-HttpClient/4.5.6 (Java/1.8.0_191)
</requestHeader>
<responseData class="java.lang.String">{"Message":"The request entity's media type 'multipart/form-data' is not supported for this resource.'}</responseData>
<cookies class="java.lang.String"></cookies>
<method class="java.lang.String">POST</method>
<queryString class="java.lang.String">--jBtzRzXGjCNVf_3UH8LfxguE6qR9_xH--
</queryString>
<java.net.URL>awesome_route_path</java.net.URL>
</httpSample>
The issue is also not with the sql syntax. It run fine from another function in the controller when parameters were given through the URL.
I also tried filling the files upload with the path and a paramter name and then in parameters to add the file and It always gives out the same error code. I just want the JSON parameters to fill the function's argument so it can be used as shown in code. What is it I'm missing? Thanks.
Add HTTP Header Manager as a child of the HTTP Request sampler
Configure it to send Content-Type header with the value of application/json
Make sure you have Use multipart/form-data for POST NOT CHECKED in the HTTP Request sampler
More information: REST API Testing - How to Do it Right
I am trying to do a POST in jmeter with a json as the body data but I just get a 400 back. The URL I am sending to only accepts json. I have used the same curl in Postman and it worked just fine. I have tried putting the json in the parameters as a value with no name and that didnt work.
I am just trying to send {"uid":"jmtest","name":"newdevice"}.
Sorry I cant post more links.
The sampler result is
Thread Name: QA test 1-1
Sample Start: 2016-05-11 11:50:19 MDT
Load time: 86
Connect Time: 51
Latency: 86
Size in bytes: 282
Headers size in bytes: 244
Body size in bytes: 38
Sample Count: 1
Error Count: 1
Data type ("text"|"bin"|""): text
Response code: 400
Response message: Bad Request
Response headers:
HTTP/1.1 400 Bad Request
Server: nginx
Date: Wed, 11 May 2016 17:50:19 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 38
Connection: keep-alive
X-Request-Id: 88339ee9-b74f-4e22-b581-e3124949d067
X-Runtime: 0.030877
HTTPSampleResult fields:
ContentType: application/json; charset=utf-8
DataEncoding: utf-8
And the request looks like
/url redacted
POST data:
{"devices":{"uid":"jmtest","name":"newdevice"}
[no cookies]
Request Headers:
Connection: keep-alive
Accept: application/vnd.moneydesktop.v2+json
Content_Type: application/json
MD-SESSION-TOKEN: redacted
Content-Type: application/x-www-form-urlencoded
Content-Length: 46
Host: redacted
User-Agent: Apache-HttpClient/4.5.2 (Java/1.8.0_72)
The response data is
{
: "status":"400",
: "error":"Bad Request"
}
To send a POST HTTP Request with the JSON Data inside the body, need to add,
HTTP Header Manger into your request and set the name as 'content-type' and value as 'application/json' this will attached into HTTP request header and what ever the data inside your request body will send as json format.
Image 1:Set HTTP Header Manager,
Image 2:Set HTTP Request Body Data
Make sure your HTTP Header Manager is configured to send Content-Type header with the value of application/json
Given you have samplers like "home page" and "login" it might be the case you're missing HTTP Cookie Manager
The most straightforward way to see what's wrong is to capture requests sent by Postman (whatever it is) and JMeter by a sniffer tool like Wireshark, identify the differences and configure JMeter accordingly.
Finally, it looks like you're using some developer snapshot so approach to pass JSON payload as 1st argument without name might not work. Try switching to "Body Data" instead.
If above steps won't help update your question with screenshots of View Results Tree listener (all 3 tabs) and Postman
Check out Testing SOAP/REST Web Services Using JMeter for more tips.
This solution from Dmitri T, really worked for me.
Make sure your HTTP Header Manager is configured to send "Content-Type" header with the value of "application/json".
I have faced the same issue and it was resolved by setting the value of Content Encoding to utf-8 in http request. Please try.
First thing you might wanna do is put the payload inside "Body Data" Instead of "Parameters"
Then, add a config element "HTTP Header Manager"
And add a parameter "content-type" With corresponding value "application/json"
Now hit. Should do!
I figured out my problem. I had set Content_type instead of Content-Type so it was creating two content type headers.
Though Hasiya explain really well but missed how to find http request.
If you chose http default will not see method option .
I had given HTTP/1.1 415 Unsupported Media Type
After deleting space before of HTTP Header Manager ,It got 200 and worked like a charm
You must use body data, not parameters. cut and paste it the next tab on your request. Also you should change implementation to Java and check if your token is valid. Finally check your results from view results tree reporting item. It must be work for you.
In addition to many said above, make sure that the copy/paste of Accept, Content-Type from website doesn't have a trailing space! It costs me many hours to figure it out. Just a caution.
Just edit to add that if that mistake happens, return code is 415: Unsupported Media Type
Insert your json in body data field.
In your HTTP Header Manager set the headers stores to:
"name" : Content-Type
"value": application/json
Yes, we need to pass the Content-Type header.
I faced the same issue and it took nearly a day to figure out until I came across this link - https://www.blazemeter.com/blog/performance-test-web-services
Header:
Name: Content-Type Value: application/json;charset=utf-8
If none of the abovementioned solutions work for you (as it was for me) take a second look at the HTTP Header Manager. I had empty header line there
Removing it solved the problem
I was facing the similar issue, the size of my request body was also huge so along with updating content-type as application/json, i gave content encoding as utf-8 and it worked perfectly fine.
As per your attached pic , You have pasted the request in queryparameters , the payload must be in body part
check the screenshot you have payload in queryParam section
Setting the HTTP header manager fixed the issue for me
HTTP Header Manager:
Name: Content-type and Value: application/json has resolved issue.
I'm testing the Authorization Code Grant protocol on the instance of KeyRock GE at FIWARE-Lab using DHC web client.
So far I have succeeded on implementing the Authorization Request, and I obtain the code to be used on the Access Token Request. The URL for the Authorization Request is the following (although not executed on DHC, but on a regular browser so I can introduce my user and password):
https://account.lab.fiware.org/oauth2/authorize/?response_type=code&client_id=2122&redirect_uri=http%3A%2F%2Flocalhost%2FCallback
I have checked that the client_id and the redirect_uri are both correct against the values related with my application at my account at FIWARE-Lab.
Executing the following request (can't post images, so I'll describe)
POST
https:// account.lab.fiware.org/oauth2/token?grant_type=authorization_code&code=<code>&redirect_uri=http%3A%2F%2Flocalhost%2FCallback -- <code> is the code obtained on the Auth. Request
Authorization: Basic <XXXX> --- <XXXX> is the result of base64(client_id+":"+client_secret)
Content-Type: application/x-www-form-urlencoded
...I get the following error message:
{
"error":{
"message": "create_access_token() takes exactly 3 arguments (2 given)",
"code": 400,
"title": "Bad Request"
}
}
I've checked the authorization is correct (Basic using the OAuth credentials from my application), and I'm using the same redirect_uri used at the previous Authorization Request, and the code obtained from it.
¿What is wrong?
P.S.: If I remove any or all of the query parameters, I still get the same error
Don't pass the parameters in the url. Instead, add them to request's body as query string:
POST /oauth2/token HTTP/1.1
Host: account.lab.fiware.org
Content-Type: application/x-www-form-urlencoded
Authorization: Basic <XXXX> --- <XXXX>
Cache-Control: no-cache
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code&code=1234&redirect_uri=http%3A%2F%2Flocalhost%3A9000%2Fcodecallback.html
I suggest to follow the steps in the presentation:
Adding Identity Management and Access Control to your Application
It gives you details about what are the different requests that you have to follow and also what are the expected response of them.
I'm attempting to use the add_run API method to create new test runs on my testrail server. I am using RESTClient to test the command.
The request is POST index.php?/api/v2/add_run/1
(I have a project with id 1)
As request headers I am using Content-Type: application/json and Authorization: Basic USERNAME:PASSWORD_BASE64
request body is:
{
"name":"name",
"suite_id":1
}
Upon sending the request, I receive a "400 Bad Request" Response with the error message:
{"error":"Content-Type header invalid (use Content-Type: application\/json)"}
Since I am in fact using Content-Type: application/json as a request header I have no idea why I am getting this error or what it means. Anyone have any ideas?
one of the TestRail developers here. It's very likely that you didn't submit the Content-Type header correctly, could you please share the source snippet you used to send this request?
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.