How to extract parameters from curl request in jersey servlet? - java

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.

Related

How to convert curl call with "-i --upload-file" into java Unirest or any other http request?

The example below uses cURL to upload image file included as a binary file.
curl -i --upload-file /path/to/image.png --header "Authorization: Token" 'https://url....'
It works fine. I need to make this request from my Java application.
I have tried next code
URL image_url = Thread.currentThread().getContextClassLoader().getResource("jobs_image.jpg");
String path = image_url.getFile();
HttpResponse<String> response = Unirest.post(uploadUrl)
.header("cache-control", "no-cache")
.header("X-Restli-Protocol-Version", "2.0.0")
.header("Authorization", "Bearer " + token + "")
.field("file", new File(path))
.asString();
However, it returns status 400 Bad Request.
Is there any way to call such request from Java?
This is a request from LinkedIn v2 API:
https://learn.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/share-on-linkedin?context=linkedin/consumer/context#upload-image-binary-file
After several hours of banging my head against the wall, I finally figured out how to convert the curl call into a RestClient one (I'm using Ruby on Rails).
I think the problem you're having is that you have to pass the MIME type as the Content-Type in the request headers.
I'm using MiniMagick to figure out the MIME type of the image I'm uploading to LinkedIn. MiniMagick can also give you the binary string of the image that LinkedIn requires, so it's a win-win situation.
This is the call that finally worked:
file = MiniMagick::Image.open(FILE_PATH)
RestClient.post(UPLOAD_URL, file.to_blob, { 'Authorization': 'Bearer TOKEN', 'Content-Type': file.mime_type })
Below method will upload the image to linkedIn
Reference : https://learn.microsoft.com/en-us/linkedin/marketing/integrations/community-management/shares/vector-asset-api#upload-the-image
private void uploadMedia(String uploadUrl,String accessToken) throws IOException {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization","Bearer "+accessToken);
byte[] fileContents = Files.readAllBytes(new
File("path_to_local_file").toPath());
HttpEntity<byte[]> entity = new HttpEntity<>(fileContents, headers);
restTemplate.exchange(uploadUrl,HttpMethod.PUT, entity, String.class);
}
I think the curl command
curl -i --upload-file /path/to/image.png --header "Authorization: Token" 'https://url....'
uses PUT while your Java client uses POST
Source: The man page of curl.
-T, --upload-file <file>
This transfers the specified local file to the remote URL. If
there is no file part in the specified URL, Curl will append the
local file name. NOTE that you must use a trailing / on the last
directory to really prove to Curl that there is no file name or
curl will think that your last directory name is the remote file
name to use. That will most likely cause the upload operation to
fail. If this is used on an HTTP(S) server, the PUT command will
be used.
Not sure if this is the actual problem though. Your API doc link actually specifies POST.

can we use content type octet stream and json together?

I have created a one rest service for uploading file.
My service consume Stream for file and Map of String for some info.
#RequestMapping(value = "/upload" , method = RequestMethod.POST)
public void upload(InputStream file,Map<String, String> fileInfoMap) {}
If yes then how to call service with POSTMAN?
if not then please suggest some alternatives?
add multipart/mixed content_type in postman , under body section select form-data like below attached image
Try with postman if that doesn't work try curl
curl -i -X POST -H "Content-Type: multipart/mixed" -F "fileInfoMap="name=xxx&age=24&location=yyy";type=application/x-www-form-urlencoded" -F "file=#somefile.zip" http://localhost:8080/upload

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.

Get data in java when http request sent by curl command

Does anyone know how to get data in java when http request sent by curl command "--data"?
For example :
curl --data { Name : username , Gender : gender , Age : age } -X PUT http://localhost:8080/user/folder -v
I want to know how to get data { Name :username ,..... age } using curl command --data.
I use the method in REST Web service which is used jersey framework and java .
Since you PUT data when you use curl this way, all you need to do is to implement a PUT request handler. In theory at least :)
Something like
#PUT
#Path("/user/folder")
#Consumes("application/json")
public void receiveData(String data) {
......
}
edit: didn't see the -X PUT at first. you want a PUT handler not a POST handler.

Categories