【发布时间】:2015-07-27 17:51:50
【问题描述】:
我正在尝试使用 Jersey 构建一个 RESTful Web 服务。
在我的服务器端代码中,有一个名为“domain”的路径,用于显示内容。 “域”所指的页面内容只有输入正确的用户名和密码才能访问。
@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("domain")
public ArrayList<String> domainList(@Context HttpServletRequest req) throws Exception{
Environments environments = new DefaultConfigurationBuilder().build();
final ALMProfile profile = new ALMProfile();
profile.setUrl(environments.getAutomation().getAlmProfile().getUrl());
profile.setUsername((String) req.getSession().getAttribute("username"));
//Set username from input, HTML form
profile.setPassword((String) req.getSession().getAttribute("password"));
//Set password from input, HTML form
try (ALMConnection connection = new ALMConnection(profile);) {
if (connection.getOtaConnector().connected()) {
Multimap<String, String> domain = connection.getDomains();
ArrayList<String> domain_names = new ArrayList<String>();
for(String key : domain.keys()){
if(domain_names.contains(key)) domain_names.add(key);
}
return domain_names; //return the content
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
当我尝试测试是否返回了正确的内容时,我收到了一个错误(状态=405,原因=不允许方法)。下面是我的客户端测试。
public static void main(String[] args){
Environments environments = new DefaultConfigurationBuilder().build();
final ALMProfile profile = new ALMProfile();
profile.setUrl(environments.getAutomation().getAlmProfile().getUrl());
profile.setUsername("username"); //Creating a profile with username and password
profile.setPassword("password");
ClientConfig config = new ClientConfig();
Client client = ClientBuilder.newClient(config);
WebTarget target = client.target(getBaseURI());
String response = target.path("domain").request().accept
(MediaType.APPLICATION_JSON).get(Response.class).toString();
//Above is the GET method I see from an example,
//probably is the reason why 405 error comes from.
System.out.println(response);
}
private static URI getBaseURI() {
return UriBuilder.fromUri("http://localhost:8080/qa-automation-console").build();
}
servlet 配置良好。我们还有其他路径成功运行。 我怀疑原因可能来自我使用 GET 方法来完成应该是 POST 的工作。 但是我不熟悉可以使用的 Jersey 方法。
有人知道我可以用来测试功能的任何方法吗?
【问题讨论】:
-
请通读 Jersey 文档的the client documentation。服务器端代码中的 cmets 声明用户名和密码应通过表单获取,但您可以从会话中检索它们。虽然 RESTful 服务通过 HttpRequest 对象提供对会话的访问,但通过 JAX-RS 对会话的支持并非直接支持 - 出于可伸缩性和安全性等一些很好的原因。
标签: java rest jaxb jersey jax-rs