How to access request header values ​​in Java Restlet?

I am developing web services using Restlet Java .

To do this, I want to protect some web services from unauthorized clients. Therefore, I wrote a filter class. In this filter class, I want to get request headers . But I get the following error -

java.lang.ClassCastException: org.restlet.engine.http.HttpRequest cannot be cast to javax.servlet.http.HttpServletRequest 

Coding -

 public class MyFilter extends Filter { @Override protected int beforeHandle(Request request, Response response) { int result = STOP; HttpServletRequest httpReq = (HttpServletRequest) request; String user_token = httpReq.getHeader("auth"); if(user_token.equals("xyz")) { result = CONTINUE; } return result; } } 

Please suggest me a way to access request header values ​​in Java Restlet?

+4
source share
5 answers

I solved my problem using

 Form headers = (Form) request.getAttributes().get("org.restlet.http.headers"); String user_token = headers.getFirstValue("Location"); 

I found this link http://blog.yudongli.com/2009/12/get-request-header-in-restlet_13.html useful.

+3
source

Also note that Restlet provides an API for a RESTful application. This means that you can access the standard headers using this API. In most cases, you do not need to use an attribute named "org.restlet.http.headers".

For example, if you want to set the Location header in the response, you add this code:

 getResponse().setLocationRef("http://..."); 

Otherwise, since you are talking about security, Restlet provides a common API to support this aspect (see the ChallengeAuthenticator, Verifier, Enroler classes).

Hope this helps you. Thierry

+2
source

If you are using Restlet 2.1-RC3, this is the way to get it

  Series<Header> headers = (Series<Header>) getRequestAttributes().get("org.restlet.http.headers"); String auth = headers.getFirstValue("auth"); 

This is exactly how it worked for me. None of the answers above have done this. Hope this helps.

+1
source

How do you deal with the search for identifier analysis in the GET header from a client request? Do you approach this the same way?

Because:

 Form headers = (Form) getRequestAttributes().get("org.restlet.http.headers"); 

returns all header information and

 String hID = headers.getFirstValue("Location"); 

gets location (s)

How do you deal with parsing an identifier?

0
source
 Series headers = (Series) getRequestAttributes().get("org.restlet.http.headers"); String origin = headers.getFirstValue("Origin");` 

This is just an example of getting an Origin header. If you want a location, just change it to headers.getFirstValue ("Location");

As in the new version of Restlet, getRequestAttributes (). get () returns a series instead of a form.

0
source

Source: https://habr.com/ru/post/1492277/


All Articles