4

我想使用 RestEasy 客户端框架测试我的 REST 服务。在我的应用程序中,我使用的是基本身份验证。根据 RestEasy 文档,我使用org.apache.http.impl.client.DefaultHttpClient来设置身份验证凭据。

对于 HTTP-GET 请求,这工作正常,我被授权并且我得到了我想要的结果响应。

但是,如果我想在请求的 HTTP 正文中使用 Java 对象(在 XML 中)创建 HTTP-Post/HTTP-Put 怎么办?有没有办法在我使用时自动将 Java 对象编组到 HTTP-Body 中org.apache.http.impl.client.DefaultHttpClient

这是我的身份验证代码,有人可以告诉我如何在不编写 XML-String 或使用 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 


}

是否有可能使用服务器端模拟框架,然后编组并将我的对象发送到那里?

4

1 回答 1

2

好的,让它工作,这是我的新代码:

@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);

 }
于 2012-10-23T16:45:32.563 回答