RestEasy 客户端身份验证和带编组的 HTTP 放置 [英] RestEasy Client Authentication and HTTP Put with Marshalling
问题描述
我想使用 RestEasy 客户端框架测试我的 REST 服务.在我的应用程序中,我使用的是基本身份验证.根据 RestEasy 文档,我使用 org.apache.http.impl.client.DefaultHttpClient
来设置身份验证的凭据.
I want to test my REST-Service using the RestEasy Client Framework.
In my application I am using Basic Authentication. According to the RestEasy documentation I am using the org.apache.http.impl.client.DefaultHttpClient
to set the Credentials for Authentication.
对于 HTTP-GET 请求,这工作正常,我已获得授权,并且得到了我想要的结果响应.
For an HTTP-GET Request this works fine, I am authorized and I get the result Response which I wanted.
但是如果我想在请求的 HTTP 正文中使用 Java 对象(在 XML 中)创建 HTTP-Post/HTTP-Put 怎么办?当我使用 org.apache.http.impl.client.DefaultHttpClient
时,有没有办法自动将 Java 对象编组到 HTTP 正文中?
But what if I want to make a HTTP-Post/HTTP-Put with an Java Object (in XML) in the HTTP-Body of the Request? Is there a way to automatically marshall the Java Object into the HTTP-Body when I am using the org.apache.http.impl.client.DefaultHttpClient
?
这是我的身份验证代码,谁能告诉我如何在不编写 XML-String 或使用 InputStream 的情况下制作 HTTP-Post/HTTP-Put?
Here's my code for authentication, can someone tell me how to make an HTTP-Post/HTTP-Put without writing an XML-String or using an InputStream?
@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
}
是否有可能使用服务器端模拟框架,然后将我的对象编组并发送到那里?
Is there maybe a possibillity to use the Server-side Mock Framework and then marshall and send my object there?
推荐答案
好的,搞定了,这就是我的新代码:
@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);
}
员工资源:
@Path("/employee")
public interface EmployeeResource {
@PUT
@Consumes({"application/json", "application/xml"})
void createEmployee(Employee employee);
}
这篇关于RestEasy 客户端身份验证和带编组的 HTTP 放置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!