Jersey Test Equivalent to curl request - java

First trip into the Java web services world. Trying to write a test for a post request. The post looks like this in curl:
url -v -X POST -H 'Content-Type: application/json' -d '{"transaction_zips": ["78732"],"condition": "good"}' http://localhost:8080/PricingService/vin/1GTEC19J37E152026/usedValues
I've attempted:
#Test
public void testVinPricing200() {
int status = target.path("PricingService/vin/1GTEC19J37E152026/usedValues").request(MediaType.APPLICATION_JSON_TYPE).
post(Entity.entity("{\"transaction_zips\": [\"78732\"],\"condition\": \"good\"}", MediaType.APPLICATION_JSON)).getStatus();
assertEquals(200, status);
}
This results in:
Failed tests: testVinPricing200(com.comp.platform.PricingServiceTest): expected:<200> but was:<406>
So the question is simple, I'm obviously not posting correctly, what am I doing wrong?

The difference between your curl request and your junit test in your junit test you are requesting a response of type MediaType.APPLICATION_JSON_TYPE, but your webservice is not capable of responding via JSON.
Http Status code: 406
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.

Related

How to send a PUT request with multipart/form-data body with Java Http Client?

I am using the HttpClient and HttpRequest available on java.net.http. I have successfully sent some GET and POST requests, but I have no clue about how to send a PUT/POST request with multipart/form-data body:
HttpRequest dataRequest = HttpRequest.newBuilder()
.header("accept", "*/*")
.header("Content-Type", "multipart/form-data")
// .POST() ??
.uri(URI.create(DATA_URL)
.build();
The curl equivalent of this request would be something like:
curl -X PUT "https://www.example.com/data" -H "accept: */*" -H "Content-Type: multipart/form-data" -F "file=#audiofile.wav;type=audio/wav"
Should I use some kind of BodyPublishers in the POST() or PUT() method in order to achieve that? Any clue?
Multipart/form-data is not supported out of the box by the HttpClient API yet.
In JDK 16 there is a new HttpRequest.BodyPublishers.concat(BodyPublisher...) method that can be used to help build a request body built from the concatenation of bytes coming from heterogeneous sources.
But you would have to manually compose all the different parts, and handle base64 encoding when/if that's needed.
You could also try out methanol

Jersey: Get binary data from post request

I am trying to build a Java server using Jersey, which accepts POST requests with binary data.
Here is a sample request it should accept:
curl -XPOST --data-binary #/path/to/some/file "localhost:<port>/myServer/processMyData"
I implemented something that currently doesn't work:
#Path("/myServer")
class MyServer {
#POST
#Path("/processMyData")
#Consumes(MediaType.APPLICATION_OCTET_STREAM)
String processMyData(byte[] payload) {
return "Sanity check string";
}
}
When I run the curl command (see above) at the first time, I get the error:
curl: (56) Recv failure: Connection reset by peer
Then, curl prints nothing when I call it again, and exits with status 0, while the server ignores everything.
What am I doing wrong?
Note: When I remove the --data-binary #/path/to/some/file clause from the curl command, the request is accepted on the server. How can I accept the binary data in Jersey?
Answering myself...
It is very simple, the removal of #Consumes(MediaType.APPLICATION_OCTET_STREAM) solved the problem

How to extract parameters from a restful post request using jersey and convert it into parameterized form? [duplicate]

I am making a curl post restful request to my jersey servlet in the form
curl -i -X POST -d "debit_user_id=/custome/mobile_number:917827448775"http://localhost:8080/switch/apikongcall.do/transactions
I need to fetch the debit_user_id in my servlet, code for my Post method is
#POST
//#Path("/transactions")
//#Consumes(MediaType.APPLICATION_JSON)
public Response createTrackInJSON(#QueryParam("debit_user_id") String debit_user_id) {
//Log logger = null;
this.logger = LogFactory.getLog(getClass());
this.logger.info("Inside post method"+debit_user_id);
String response = debit_user_id;
//String response = "testParam is: " + recipient_id + "\n";
//String result = "Track saved : " + track;
return Response.status(200).entity(response).build();
But my debit_user_id is coming as null. Is it the correct way to make the curl restful request or the way I am extracting it in my servlet is wrong.
I am new to jax-rs. Thanks in advance for the help.
The -d option to curl passes in a url encoded form parameter. You have to change #QueryParam to #FormParam to make the given Curl command work. Also, just specify the parameter name as mobile_number without the pathing that you used in you curl command, like so:
curl -i -X POST -d "debit_user_id=mobile_number:917827448775" http://localhost:8080/switch/apikongcall.do/transactions
maps to
#POST
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response createTrackInJSON(#FormParam("mobile_number") String debit_user_id) {
...
}
If you do in fact want a query parameter, your curl command would need to change:
curl -i -X POST http://localhost:8080/switch/apikongcall.do/transactions?mobile_number=917827448775
For security reasons, it's probably better to keep the mobile number in the message body, so I'd use the FormParam instead of the QueryParam.

Query parameter not being extracted - JAX-RS and Jersey

I'm using Jersey 2.19 to implement a REST API but I'm having difficulty using #QueryParam to extract the query parameters from a POST request even though my resource method is being called.
This is my resource method:
#POST
#Produces(MediaType.TEXT_PLAIN)
public Response test(#QueryParam("test-param") String testParam)
{
String response = "testParam is: " + testParam + "\n";
return Response.status(Response.Status.OK).entity(response).build();
}
I'm using cURL to submit the HTTP POST request as follows:
curl -X POST http://192.168.0.2:8080/myApp/test --data test-param=Hello
The value returned is always null.
What am I doing wrong?
The --data in curl will provide the whole text test-param=Hello. The correct way to request it is:
curl -X POST http://192.168.0.2:8080/myApp/test?test-param=Hello
try to use curl -X POST '192.168.0.2:8080/myApp/test?test-param=Hello';
-d, --data
(HTTP) Sends the specified data in a POST request to the HTTP server, in the same way that a browser does when a user has filled in an HTML form and presses the submit button. This will cause curl to pass the data to the server using the content-type application/x-www-form-urlencoded. Compare to -F, --form.

#FormParam parameter always null in my JAX-RS resource service

Here is a service that I request with a curl :
time curl -i -XPOST 'http://localhost:9080/my/service' -H "Authorization:OAuth MyToken" -H "Content-Type: application/json" -d "ids=516816b2e4b039526a235e2f,516816b2e4b039526a235e2f"
The resource :
#Path("/my")
#Consumes({"application/xml", "application/json"})
#Produces({"application/xml", "application/json", "text/json"})
#Restricted
public class MyResource {
#POST
#Path("/service")
public Map<String ,Object> myService(#FormParam("ids") String myIds) {
// service things
}
}
That service worked fine, but it suddenly fails. Now the parameter myIds is always null, and the result of the curl is 400 bad request...
I didn't change anything in this resource so it should still be working.
If anybody has an idea, let me know.
Thanks!
In your curl-command, you are posting form data along with the Content-Type: application/json. Clearly this data is not valid JSON, hence the 400 bad request.
If you want to post form data, you need to use the content type application/x-www-form-urlencoded

Categories