Dmitri Boulanov
Dmitri Boulanov

Reputation: 87

How to reflect the incoming GET request in text?

I'm using Spring MVC and Springboot (assume latest version) to put up a simple web service that returns some text.

I was able to figure out how to use @RequestMapping and @PathVariable annotations to show one of the URL path variables as a response from the server (e.g. if the user goes to .../my_user_id/ in the browser, they can then see some text in the browser that includes that user_id... since the service returned it as a response).

I need help with figuring out how to capture the GET HTTP request the user's browser makes and then display it in text form as a response in the browser (I want to display the headers and the request body as plain text).

I've done some research, but none of the solutions available work properly. Is anyone aware of the right approach / feasibility here?

An approach I tried:

Some threads on the error I get back when I tried the above approach:

More on Spring MVC, which I'm heavily using:

Anyhow. When using the below @Controller, I get an error:

@RestController
public class HelloController {

@RequestMapping("/")
public String index() {
    return "Welcome to your home directory";
}

@RequestMapping(value="/mydata/{userId}", method=RequestMethod.GET)
public String printTheUser(@PathVariable String userId) {
    return "The data for " + userId + " would live here";
}


@RequestMapping("/summary_data/")
public String index3() {
    return "All summary data would appear here";
}

private String server = "localhost";
private int port = 8080;

@RequestMapping("/request_mirror/**")
public @ResponseBody String mirrorRest(@RequestBody String body, HttpMethod method, HttpServletRequest request,
    HttpServletResponse response) throws URISyntaxException {
    URI uri = new URI("http", null, server, port, request.getRequestURI(), request.getQueryString(), null);

    RestTemplate restTemplate = new RestTemplate();

    ResponseEntity<String> responseEntity =
        restTemplate.exchange(uri, method, new HttpEntity<String>(body), String.class);

    return responseEntity.getBody();
    }
}

When running this code and navigating to localhost:8080/request_mirror/stuff3/, I get the following error:

Whitelabel Error Page.   This application has no explicit mapping for /error, so you are seeing this as a fallback.
Mon Feb 08 15:41:13 EST 2016
There was an unexpected error (type=Bad Request, status=400).
Required request body content is missing:    org.springframework.web.method.HandlerMethod$HandlerMethodParameter@a35a9b3f

Now, when I try a different approach (another @Controller) - the code looks like:

@Controller
@RequestMapping("/site")
public class SecondController{

@Autowired
private HttpServletRequest request;

@RequestMapping(value = "/{input:.+}", method = RequestMethod.GET)
public ModelAndView getDomain(@PathVariable("input") String input) {

    ModelAndView modelandView = new ModelAndView("result");

    modelandView.addObject("user-agent", getUserAgent());
    modelandView.addObject("headers", getHeadersInfo());

    return modelandView;

}

//get user agent
private String getUserAgent() {
    return request.getHeader("user-agent");
}

//get request headers
private Map<String, String> getHeadersInfo() {

    Map<String, String> map = new HashMap<String, String>();

    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String key = (String) headerNames.nextElement();
        String value = request.getHeader(key);
        map.put(key, value);
    }

    return map;
}
}

For the above code (SecondController), (sourced from http://www.mkyong.com/java/how-to-get-http-request-header-in-java/), I get the following error, when I try to navigate to localhost:8080/site/stuff123456789... (but I can see the header keys and values from the request in the Map upon inspection... just not sure how to display them as text in the browser as the response).

This application has no explicit mapping for /error, so you are seeing this as a fallback.

 Mon Feb 08 16:10:47 EST 2016
There was an unexpected error (type=Internal Server Error, status=500).
Circular view path [stuff123456789]: would dispatch back to the current handler URL [/site/stuff123456789] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)

Upvotes: 2

Views: 1824

Answers (1)

tanenbring
tanenbring

Reputation: 780

EDIT: Use the HttpEntity to get the body in case it's empty.

I'm not sure exactly what you're trying to achieve, but think this might be close:

@RequestMapping(value="/echoRequest")
public @ResponseBody String echoRequest(HttpEntity<String> httpEntity, HttpServletRequest req) {
    String out = "";
    List<String> names = req.getHeaderNames();
    for (String name : names) {
        out += (name + ": " + req.getHeader(name) + "\n");
    }
    if (httpEntity.hasBody()) {
        out += httpEntity.getBody();
    }
    return out;
}

Upvotes: 1

Related Questions