我对一般的Web服务并不熟悉,并且一直在做大量的研究,但我目前无法捕获我需要用于身份验证目的的请求头。无法在REST风格的Web服务上捕获请求
以下是这个场景:在将请求头添加用户名/密码组合后,我有一个Android客户端在我的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 = "[email protected]";
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();
}
}
}
非常感谢您remigio!你的解释和你提供的链接真的很有用。遵循你的例子,我可以通过使用'@Context HttpHeaders headers'和'headers.getRequestHeaders()'来捕获头文件。 –