我想使用RestEasy Client Framework测试我的REST服务.
在我的应用程序中我使用基本身份验证.根据RestEasy文档,我使用org.apache.http.impl.client.DefaultHttpClient来设置身份验证的凭据.
对于HTTP-GET请求,这工作正常,我被授权,我得到了我想要的结果响应.
但是,如果我想在请求的HTTP主体中使用Java对象(在XML中)创建HTTP-Post / HTTP-Put,该怎么办?当我使用org.apache.http.impl.client.DefaultHttpClient时,有没有办法自动将Java对象编组到HTTP-Body中?
这是我的身份验证代码,有人可以告诉我如何在不编写XML字符串或使用InputStream的情况下创建HTTP-Post / HTTP-Put吗?
@Test
public void testClient() throws Exception {
DefaultHttpClient client = new DefaultHttpClient();
client.getCredentialsProvider().setCredentials(
new AuthScope(host, port),
new UsernamePasswordCredentials(username, password));
ApacheHttpClient4Executor executer = new ApacheHttpClient4Executor(
client);
ClientRequest request = new ClientRequest(requestUrl, executer);
request.accept("*/*").pathParameter("param", requestParam);
// This works fine
ClientResponse<MyClass> response = request
.get(MyClass.class);
assertTrue(response.getStatus() == 200);
// What if i want to make the following instead:
MyClass myClass = new MyClass();
myClass.setName("AJKL");
// TODO Marshall this in the HTTP Body => call method
}
是否有可能使用服务器端模拟框架然后编组并将对象发送到那里?
最佳答案 好的,让它工作,这就是我的新代码:
@Test
public void testClient() throws Exception {
DefaultHttpClient client = new DefaultHttpClient();
client.getCredentialsProvider().setCredentials(
new AuthScope(host, port),
new UsernamePasswordCredentials(username, password));
ApacheHttpClient4Executor executer = new ApacheHttpClient4Executor(
client);
RegisterBuiltin.register(ResteasyProviderFactory.getInstance());
Employee employee= new Employee();
employee.setName("AJKL");
EmployeeResource employeeResource= ProxyFactory.create(
EmployeeResource.class, restServletUrl, executer);
Response response = employeeResource.createEmployee(employee);
}
EmployeeResource:
@Path("/employee")
public interface EmployeeResource {
@PUT
@Consumes({"application/json", "application/xml"})
void createEmployee(Employee employee);
}