How to pass object in the header with post man post request? - java

I'm using postman and trying to pass an object in the header but getting an error for the converting from string to object... how would I do it right?
I'm attaching pictures from postman:
https://imgur.com/a/5wAxIYf
this is the code on the server:
#RequestMapping(
path= arrayOf(
"/wristbands/upload",
"/wristbands/upload/"),
method = arrayOf(RequestMethod.POST),
consumes = arrayOf(MediaType.APPLICATION_JSON_UTF8_VALUE))
open fun wristbandProcessNewAlgorithem(#RequestHeader(name = "X-V", required = true) wristbandRecords: WristbandRecordNewInputDTO): ResponseEntity<*>{
var res=wristbandProcessingService.processWristbandNewAlgorithem(wristbandRecords)
return ResponseEntity(res,HttpStatus.OK)
}
What am I doing wrong?
Thank you

Solution:
I think I found solution and it was moving the object from the header to the body and changing the code to be like this:
#RequestMapping(
path= arrayOf(
"/wristbands/upload",
"/wristbands/upload/"),
method = arrayOf(RequestMethod.POST),
headers = arrayOf("X-V"),
consumes = arrayOf(MediaType.APPLICATION_JSON_UTF8_VALUE))
open fun wristbandProcessNewAlgorithem(#RequestBody wristbandRecords: WristbandRecordNewInputDTO): ResponseEntity<*>{
var res=wristbandProcessingService.processWristbandNewAlgorithem(wristbandRecords)
return ResponseEntity(res,HttpStatus.OK)
}

Related

Retrofit path encode except character?

I use retrofit and my interface below
#GET("{link}")
fun search(#Path(value = "link", encoded = true) link: String?): Call<Any>
Do I need to use encoded for all link except character '?'.
Example:
Link -> /api/search?&query=تست
Encoded link by retrofit -> api/search%3F&query=%D8%AA%D8%B3%D8%AA
I need this link-> api/search?&query=%D8%AA%D8%B3%D8%AA
I need don't convert character '?' to %3F.
do is anyway?
#Url should be used for this instead of #Path
#GET
Call<ResponseClass> list(#Url String url);
It works fine with full URL and a path that is used then with base URL.
Retrofit retrofit = Retrofit.Builder()
.baseUrl("https://website.com/");
.build();
MyService service = retrofit.create(MyService.class);
service.exampleCall("https://another-website.com/example");
service.anotherExampleCall("/only/path/part");
Don't use Path ,you can use #Query in your method,it won't convert ? to %3F .
You can change your method to
#GET("api/serach")
fun search(#Query("query") value: String?): Call<Any>
For example,your value is "aolphn",this code will access
http(s)://xxx/api/search?query=aolphn
? will appended automatically.
I find a solution, must use Interceptor for the request.
class RemoveCharacterInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val path = request.url().toString()
val string = path.replace("%3F", "?") // replace
val newRequest = request.newBuilder()
.url(string)
.build()
return chain.proceed(newRequest)
}
}
and add to httpClient
val httpClient = OkHttpClient.Builder()
httpClient.addInterceptor(RemoveCharacterInterceptor())

Spring boot can't find field form font-end

I send request from Angular5 to REST API (spring boot)
but spring boot can't find the value of key (it shows null),
on top image you can see the raw data that I'm sending from postman.
in spring boot I'm creating a class and field to receive data.
In controller I'm already putting the #RequestBody
Here is my controller:
#RequestMapping(value = "/edit/barcode_option", method = arrayOf(RequestMethod.POST))
fun editBarCodeOption(model: Model,
request: HttpServletRequest,
response: HttpServletResponse,
#RequestBody barcodeForm: SKBarcodeForm): ResponseEntity<*>?{
(barcodeService.editBarcodeOption(barcodeForm)).let { barcodeData ->
return responseOk("ok")
}
return responseBadRequest()
}
and the kotlin class:
class SKBarcodeForm {
var id: Long? = null
var barcodeId: String? = null
var barcodeName: String? = null
var barcodeBrand: String? = null
var isHidingProfile: Boolean? = null
var isWasteAfterUsed: Boolean? = null
var isHaveToSeparate: Boolean? = null
}
thank you for help :D
Try to remove the prefix 'is' from your boolean properties.

JAVA API , JERSEY / POST not working

So I have in my code POST method :
#POST
#Path("/send/{userPost}")
#Consumes(MediaType.APPLICATION_JSON)
#Produces("application/json")
public Response sendUser(#PathParam("userPost") String userPost ) {
List<Post>userPosts = new ArrayList();
Post post = new Post(99,userPost,"Bartek Szlapa");
userPosts.add(post);
User user = new User(99,"Bartek","Szlapa",userPosts);
String output = user.toString();
return Response.status(200).entity(output).build();
}
unfortunately its not working. I'm getting 404 error. Server is configured correctly because other methods work perfectly. Funny thing is that when I remove {userPost} , parameter : #PathParam("userPost") String userPost and send empty request : http://localhost:8080/JavaAPI/rest/api/send it works - I'm getting new User object with null at some fields. Do you know why I cannot send parameter ? Thanks in advance for help! :)
What you are sending is not a path parameter to send your value as a path parameter based on your api , let us say you are trying to send "test"
http://localhost:8080/JavaAPI/rest/api/send/test
if you want to use query params
#POST
#Path("/send")
#Consumes(MediaType.APPLICATION_JSON)
#Produces("application/json")
public Response sendUser(#QueryParam("userPost") String userPost ) {
and your request should be
http://localhost:8080/JavaAPI/rest/api/send?userPost=test
Your "userPost" parameter is not in the Path : localhost:8080/JavaAPI/rest/api/send?=test
You defined this path :
#Path("/send/{userPost}")
So, your URI should be :
localhost:8080/JavaAPI/rest/api/send/test

How to extract parameters from an object to show in parameters in documentation

I have the following API endpoint:
#ApiResponses(
value = {
#ApiResponse(code = 200, message = "OK",
responseHeaders = {
#ResponseHeader(name = "X-RateLimit-Limit", description = "The defined maximum number of requests available to the consumer for this API.", response = Integer.class),
#ResponseHeader(name = "X-RateLimit-Remaining", description = "The number of calls remaining before the limit is enforced and requests are bounced.", response = Integer.class),
#ResponseHeader(name = "X-RateLimit-Reset", description = "The time, in seconds, until the limit expires and another request will be allowed in. This header will only be present if the limit is being enforced.", response = Integer.class)
}
)
}
)
#ApiOperation(httpMethod = "GET", hidden = false, nickname = "Get Network Availability in JSON", value = "Get network availability for a product", response = AvailableToPromise.class, position = 1)
#RequestMapping(value = "/{product_id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> networkAvailabilityJsonResponse(
#RequestHeader HttpHeaders headers,
#PathVariable("product_id") String productId,
#Valid NetworkAvailabilityCmd cmd, //query params
BindingResult result)
throws Exception {}
}
Certain parameters, such as key are taken from the query and mapped into this object through Spring MVC.
However, in the parameters section of my endpoint in the swagger-ui, it's showing me a few odd things:
None of the variables that are in NetworkAvailabilityCmd show in this parameters list, and cmd itself shows as being located in the request body (it's actually located in the query). Is there a way to hide cmd and extract the params inside this object to show on the params list? I'd like the params list to look like this (with more params):
I'm able to do this if I use #ApiImplicitParams on the method endpoint, and write out each of the params. However, this NetworkAvailabilityCmd is used for many endpoints, and having the list of params on each endpoint is very messy. Being able to extract the variables from in the object would be far cleaner, and would prevent people from forgetting to add the entire list to new endpoints.
I imagine that it requires an annotation on NetworkAvailabilityCmd cmd, and potentially something on the variables in that class, but I can't seem to find what I'm looking for in the docs.
Thanks!
I found out that adding #ModelAttribute worked magically. This annotation is from Spring.

How to deal with dot in an url path in writing service

I am writing a "GET" endpoint looks like following:
#RequestMapping(value = "/{configSetId}/{version}", method = RequestMethod.GET, produces = { "application/json" })
public ResponseEntity<List<Metadata>> getMetadatasByConfigSetIdAndVersion(
#PathVariable("configSetId") final String configSetId,
#PathVariable("version") final String version) {
return ResponseEntity.ok(metadataService.getMetadatasByConfigSetIdAndVersion(configSetId, version));
}
So I can send a "GET" request to localhost:8080/{configSetId}/{version}, for example: localhost:8080/configSet1/v1
But the problem is if the version is "v1.02", then the ".02" will be ignored and the version I got is v1. How can I avoid this behaivor? Thank you!
Since "." is special character so don't use it directly on your request.
Instead of
v1.02
Just try
v1%2E02
Where %2E is URL encoding of ".".
For more information, please refer to this link HTML URL Encoding

Categories

Resources