How to resolve URI parameters in string URL through java/spring code? - java

I have url like http://www.example.com/api/{uriparam}/something
How should I replace the uriparam with my parameter call test?
So that it will be like http://www.example.com/api/test/something

In rest API its called as path, to do that, here is sample of controller using path. here is sample with jax rs.
#Path("/testUrl/{data}")
#GET
public String checkPending(#PathParam("data") String data) {
String yourUrl = "http://www.example.com/api/" + data + "/something";
return yourUrl;
}

You can use org.springframework.web.util.UriComponentsBuilder as below :-
Map<String, String> parameters = new java.util.HashMap<String,String>();
parameters.put("uriparam","test");
String url = UriComponentsBuilder.fromHttpUrl("http://www.example.com/api/{uriparam}/something".trim()).buildAndExpand(parameters).encode().toString();
it will return you the required url

Related

How to the get wildcard path variable in the controller

I have a controller:
#PostMapping("/name/**")
public Mono<String> doSomething(HttpEntity<byte[]> requestEntity,
ServerHttpRequest serverHttpRequest) {
String restOfTheUrl = //the ** part is what i need here
return webClient.forwardRequest(requestEntity, serviceUrl + "/" + restOfTheUrl);
}
How do I obtain the URL string (including all query params) thats after the /name/ ?? basically I need the ** part. Of course I can remove the /name/ from serverHttpRequest.getPath(..) but is there a better way?
#PostMapping("/name/{*path}")
public Mono<String> doSomething(#PathVariable("path") String path) {...

Change URL pattern of rest API

#Path("/ftocservice")
public class RestService {
#Path("{f}")
#GET
#Produces("application/json")
public Response convertFtoCfromInput(#PathParam("f") float f)
throws Exception {
DbCon db = new DbCon();
ArrayList<Student> students = db.getStudentList();
JSONArray jsonArray = new JSONArray(students);
String result = jsonArray.toString();
return Response.status(200).entity(result).build();
}
}
I'm using above source code to generate rest API and user is requesting through the API as follows.
http://localhost:8080/RestExample/RestService/ftocservice/23
I need to change the request URL as follows.
http://localhost:8080/RestExample/RestService/ftocservice?f=23
Please help to change the source code to change request URL as given. Thanks
Change to use #QueryParam instead:
#Path("/ftocservice")
public class RestService {
#GET
#Produces("application/json")
public Response convertFtoCfromInput(#QueryParam("f") float f)
throws Exception {
DbCon db = new DbCon();
ArrayList<Student> students = db.getStudentList();
JSONArray jsonArray = new JSONArray(students);
String result = jsonArray.toString();
return Response.status(200).entity(result).build();
}
}
See this link for more info on parameter types in JAX-RS.
This tutorial by Mkyong.com is also quite nice.
use #QueryParam instead of #PathParam

How to pass two query parameters in URL

In this example, the URL for a service has the form /projection/projectionId:
#Stateless
#Path("projection")
public class ProjectionManager {
#Inject
private ProjectionDAO projectionDAO;
#Inject
private UserContext userContext;
#GET
#Path("{projectionId}")
#Produces("application/json")
public String places(#PathParam("projectionId") String projectionId) {
return projectionDAO.findById(Long.parseLong(projectionId)).getPlaces().toString();
}}
How can I pass two (or more) query parameters to access the service using this code:
#PUT
#Path("/buy")
public Response buyTicket(#QueryParam("projectionId") String projectionId, #QueryParam("place") String place) {
Projection projection = projectionDAO.findById(Long.parseLong(projectionId));
if(projection != null) {
projectionDAO.buyTicket(projection, userContext.getCurrentUser(), Integer.parseInt(place));
}
return Response.noContent().build();
}
/buy?projectionId=value1&place=value2
Take a look at https://en.wikipedia.org/wiki/Query_string for further information. And since it is HTTP PUT you cannot simply open that URL in your browser, you can write some simple REST client or use browser extension like Postman in Chrome.
Query parameter is the thing after the ? in the URI, while path parameter is the parametrer before the ? in the URI.
If you need two inputs to your method, you can go with any combination of query param and path param => four combinations
It's a good convention that path params should denote some kind of identity of the resource, because it's part of it's address, while query params more some form/shape/filtering of the response.
In your case, I'd encode both params as path parameters, so the code would look like this:
#PUT
#Path("/buy/{projectionId}/place/{place}")
public Response buyTicket(#PathParam("projectionId") String projectionId, #PathParam("place") String place){
Projection projection = projectionDAO.findById(Long.parseLong(projectionId));
if(projection != null){
projectionDAO.buyTicket(projection, userContext.getCurrentUser(), Integer.parseInt(place));
}
return Response.noContent().build();
}
The URL would look like:
${host}/buy/1337/place/42
Thanks for your input guys, I have fixed it.
It looks like I had to add the path parameter to the additional parameters, and pass additional parameters on the request, instead of the path parameter. Code looks as below,
it('should get a customer, searches with a customer name', (done) => {
var pathParams = {};
var body = {};
var additionalParams = {
queryParams: {
name: 'Ominathi'
}
};
//apigClient.invokeApi(pathParams, '/customer', 'GET', queryParams, body)
apigClient.invokeApi(pathParams, '/customer', 'GET', additionalParams, body)
.then(response => {
expect(response.status).toBe(200);
done();
})
.catch(err => {
fail(err);
done();
});
});
Thanks.
Ref: https://www.npmjs.com/package/aws-api-gateway-client

Decode WebTarget URI

I have one property in property file
appointments.deleteAppointmentwithReasonApi=api/appointment/{id}?reason={reason}
URL=http://xyz/etc/
in another file
public static final String DELETE_APPOINTMENT_REASON = PropertiesUtil.getPropertyValueFromKey(REST_WEBSERVICE_URLS_PROP_FILE,
"appointments.deleteAppointmentwithReasonApi"); // To get API name
public static final String URL = ServicesUtil.getURL(); // to get endpoint URL
In my java API call, I gave something like this
WebTarget target = client.target(CommonConstants.URL)
.path(CommonConstants.DELETE_APPOINTMENT_REASON)
.resolveTemplate("id", appointmentID).resolveTemplate("reason", reason);
System.out.println(target);
My response is printing like this...
JerseyWebTarget { http://xyz/etc/api/appointment/abc-123-ced-456%3Freason=Test }
which is not hitting the proper Web Services...I want it to be like this
JerseyWebTarget { http://xyz/etc/api/appointment/abc-123-ced-456?reason=Test }
I know i need to encode URL. I am not able to do it somehow. Any suggestion ?

Redirect to External URl in Spring MVC

I am using the following configuration for controller to redirect to external url.
My application base url is http://www.testcebs.com:8080/SpringSecDemo11/
#RequestMapping(value = "/tryIt", method = RequestMethod.GET)
public String goToGoogle() {
String redirectUrl = "www.google.com";
return "redirect:" + redirectUrl;
}
On calling the "/tryIt" url it show 404. and Url goes to
http://www.testcebs.com:8080/SpringSecDemo11/www.google.com
Please suggest any way to get out of it.
Regards,
Pranav
Prefix your url string with the protocol, i.e. http://www.google.com.
final String redirectUrl = "redirect:http://www.google.com";
return redirectUrl;

Categories

Resources