无法捕获RESTful Web服务上的请求

时间:2013-01-21 06:39:59

标签: web-services rest java-ee

我是Web服务的新手,并且已经对它进行了大量的研究,但我目前无法捕获我需要用于身份验证的请求标头。

这是一个场景:我在我的JAX-RS RESTful Web服务上调用了一个login()方法,在将一个用户名/密码组合添加到请求标头之后。然后,Web服务(在JBoss AS 7.1上运行)应该捕获这些头文件。

问题是每次调用此login()方法时,请求似乎尚未得到服务,因此在执行WebServiceContext.getMessageContext()时会导致IllegalStateException。

我已经尝试将@PostConstruct注释添加到方法的标题中,但无济于事。当我这样做时,该方法似乎根本没有初始化。相反,我在调用它时会遇到ClassNotFoundException。

我如何解决这个问题?我已经坚持了几天,并在客户端和Web服务上尝试了多种不同的方法来捕获这些标题,但它们要么不适用于项目的体系结构,要么根本不能按预期工作。

这是服务的界面:

@ApplicationPath("/apppath")
@Path("/wspath")
public interface LoginService {

    @GET
    @Path("/login")
    @Produces(MediaType.APPLICATION_JSON)
    public String login();
}

这是服务的实现:

@Stateless
@Local(LoginService.class)
public class LoginServiceImpl implements LoginService {

    @Resource
    WebServiceContext wsContext;

    @Override
    public String login() {

        // This line throws an IllegalStateException.
        MessageContext msgContext = wsContext.getMessageContext();

        // TODO: Capture authentication data from headers.   
        @SuppressWarnings("unchecked")
        Map<String, List<String>> headers = (Map<String, List<String>>) msgContext.get(MessageContext.HTTP_REQUEST_HEADERS);

        // Dummy return for testing purposes.
        return "It works" + headers.toString();
    }
}

这是一个简单的JUnit测试代码,我正在尝试解决客户端的问题。

public class LoginServiceTest {

    @Test
    public void test() {

        String mEmail = "a@a.com";
        String mPassword = "aaaa";

        HttpGet request = new HttpGet("http://localhost:8080/apppath/wspath/login"); 

        String auth = Base64.encodeBytes((mEmail + ":" + mPassword).getBytes());
        request.addHeader("Authorization", "Basic " + auth);

        HttpClient httpClient = new DefaultHttpClient();

        try {
            InputStream inputStream = httpClient.execute(request).getEntity().getContent();

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));             
            String wsReturn;

            while ((wsReturn = bufferedReader.readLine()) != null) {
                System.out.println(wsReturn);
            }
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

这不是在JAX-RS服务中访问服务上下文的正确方法,WebServiceContext类被注入到JAX-WS Web服务中。在JAX-RS服务类中,您可以使用@Context注释来注入HttpServletRequest请求对象并向其询问标头。 例如:

@GET
@Path("/login")
@Produces(MediaType.APPLICATION_JSON)
public String login(@Context HttpServletRequest request);

您可以查看此link以获取有关JAX-RS的更多信息,或浏览Java EE 6 Tutorial

相关问题