问题
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.
For an HTTP-GET Request this works fine, I am authorized and I get the result Response which I wanted.
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
?
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?
回答1:
Ok, got it working, thats my new code:
@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);
}
来源:https://stackoverflow.com/questions/12972640/resteasy-client-authentication-and-http-put-with-marshalling