Get the currently used protocol name from HttpServletRequest? [duplicate] - java

This question already has answers here:
Java: String representation of just the host, scheme, possibly port from servlet request
(6 answers)
Closed 1 year ago.
I'm constructing a new URL in a Spring MVC controller, to be passed back to the client. Currently I'm trying this:
// httpRequest is the current HttpServletRequest
new URL(httpRequest.getProtocol(),
httpRequest.getServerName(),
httpRequest.getServerPort(),
httpRequest.getContextPath().concat("/foo/bar.html"));
Problem is that httpRequest.getProtocol() gives me "HTTP/1.1" instead of just "HTTP". I can trim it but wondered if there was a more elegant way.

The protocol is HTTP/1.1, since it is a specific version of HTTP. The scheme as given by ServletRequest#getSchemeitself is http:
new URL(httpRequest.getScheme(),
httpRequest.getServerName(),
httpRequest.getServerPort(),
httpRequest.getContextPath().concat("/foo/bar.html"));

In 2020 I'll suggest you use ServletUriComponentsBuilder and it's static methods, such as ServletUriComponentsBuilder#fromCurrentRequest which helps you build your URL using the previous Request.
Example:
URL url = ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/foo/bar.html")
.encode() // To encode your url... always usefull
.build()
.toUri()
.toURL()
Whatsmore, if you wanna redirect on the same app, please just return "redirect:/foo/bar.html" with status 302 and spring boot MVC will transform it into a normal redirection.
Example:
#ResponseBody
#GetMapping("/some/endpoint")
#ResponseStatus(HttpStatus.FOUND)
public ModelAndView redirectToFoo() {
return new ModelAndView("redirect:/foo/bar.html");
}

Related

Servlet get full path of request with parameters [duplicate]

This question already has answers here:
HttpServletRequest to complete URL
(12 answers)
Closed 9 months ago.
I'm using a Servlet accessible via POST request, but I've seen that parameters in POST, can be set either thanks to header parameters but also in a GET format way (/MyServlet?param1=123&param2=456) and I would need to detect it on my Servlet.
I tried to retrieve the request by using
request.getRequestURI()
but I cannot see the parameters in that case...
Do you know how can I retrieve the full path of the request in a GET parameter way ?
getParameter() returns http request parameters. Those passed from the client to the server. For example http://example.com/servlet?parameter=1. Can only return String.

SpringBoot: Timeout when the endpoint doesn't return a response [duplicate]

This question already has answers here:
Spring Boot REST API - request timeout?
(9 answers)
Closed 1 year ago.
I am new to SpringBoot and looking for a way to Timeout when endpoint takes more than 3 seconds to return the response. I tried by adding the property "server.servlet.session.timeout", but still no luck. How to achieve this? Thanks.
#GetMapping("/api")
public Data getData(){
Thread.sleep(10000);
return ....;
}
Application.properties
server.servlet.session.timeout=3s
Not sure what your http client looks like. (RestTemplate/WebClient). But using WebClient this is how you can create TimeOut for your need.
HttpClient client = HttpClient.create()
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000);
Refer this for a detailed explanation:
https://www.baeldung.com/spring-webflux-timeout

REST API is not responding while more characters given as query parameter

I am working on RESTEasy services to generate API for my application.
I tested with the below code to produce a simple string response,
#GET
#Path("/api")
public Response getUsers(#QueryParam("from") String from,) throws ProtocolException,
MalformedURLException, IOException {
return Response.status(200)
.entity("*************Hi Welcome*********************")
.build();
}
It is working fine with the following url
http://localhost:8080/myApp/f/api?from=any_string_here
But, this response available only while the query parameter value does not exceed 6246 characters.
If the query parameter value more than 6246 chars, there is no response available. Also, the browser network console shows the status code 400.
http://localhost:8080/myApp/f/api?from=more_than_6246_chars
I read that longer url needs to be send using POST, so I tried also with #POST method too for this, but browser network console shows the status code 405 and the following appears in eclipse console.
Apr 07, 2016 12:52:25 PM org.apache.tomcat.util.http.Cookies processCookieHeader
INFO: Cookies: Invalid cookie. Value not a token or quoted value
Note: further occurrences of Cookie errors will be logged at DEBUG level.
Is this longer URL is restricted by browser or RESTEasy application.
What would be the solution for this? Do I need to send more chars to my rest api parameter.
Webservers may reject requests if the URL exceeds a certain size.
Using a POST request alone does not help, you also need to decrease the URL size by putting URL parameters into the POST body.
You can try sending the parameters in request headers. I am using Jersey framework and angular JS in the front end. Sometimes I need to send a long JSON string for my application. I am sending it in the request headers and so far, I haven't got any issue like this.
My Rest Service class looks like below :
#Path("getStatus/agentName")
public class getStatus(){
#GET
public Response getStatus(#HeaderParam("header_name") String header_value){
String response = "Success" + header_value;
return Response.ok(response, MediaType.TEXT_PLAIN).build();
}
}
You can send your parameters in custom headers.
I think this should solve your problem.

Redirect to an external URL in Spring MVC [duplicate]

This question already has answers here:
Redirect to an external URL from controller action in Spring MVC
(10 answers)
Closed 9 years ago.
In a Spring Controller Action, I am using the following statement to redirect to an external URL:
String redirectUrl = "www.yahoo.com";
return "redirect:" + redirectUrl;
However, it appears that it's redirecting the url locally and not replacing the entire address bar URL with www.yahoo.com.
Ex: With the above redirection, my address bar now looks like:
http://localhost/myApp/auth/www.yahoo.com
How do I resolve this? I even tried redirecting to a view and then having the view redirect the URL, but still the same result. The only way it seems to work is if I have http://www.yahoo.com or https://www.yahoo.com But I wanted it to redirect the URL as specified and not necessarily mention the protocol. Ex: yahoo.com is similiar to http://www.yahoo.com if you go directly in the address bar.
Thanks
The protocol is required if the host is different to that of the current host
String redirectUrl = "http://www.yahoo.com";
return "redirect:" + redirectUrl;
Have a look at the redirect: prefix section from Spring Web MVC framework
A logical view name such as redirect:/myapp/some/resource will redirect relative to the current Servlet context, while a name such as redirect:http://myhost.com/some/arbitrary/path will redirect to an absolute URL.

Put request using rest

I have recently begun studyin the restlet interface. I don t know how to translate this method put using the restlet interface.
curl -X PUT http://ip:port/testdb2
How can I translate this request?
So far , i have this code :
ClientResource resource = new ClientResource("http://"+this.ip+":5984/");
// Send the HTTP GET request
Representation r=resource.get();
if (resource.getStatus().isSuccess()) {
resource.getResponseEntity().write(System.out);
}
resource.put(null);
if (resource.getStatus().isSuccess()){
resource.getResponseEntity().write(System.out);
} else
System.out.println("Error put");
How do I specify the new url?
I need this request to create a couchDB database.
Rephrasing your question, I'll use "How do I issue a PUT request to this url ..."
Per http://www.restlet.org/documentation/2.0/firstResource#part07
Perhaps something like
ClientResource dbResource = new ClientResource(
"http://"+this.ip+":5984/testdb2");
Representation r = dbResource.put(null);

Categories

Resources