Dmitri Boulanov February 2016

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:

Answers


tanenbring February 2016

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;
}

Post Status

Asked in February 2016
Viewed 3,041 times
Voted 7
Answered 1 times

Search




Leave an answer