4

我想使用RestEasy Client Framework測試我的REST服務。 在我的應用程序中,我使用基本身份驗證。根據RestEasy文檔,我使用org.apache.http.impl.client.DefaultHttpClient來設置身份驗證憑證。RestEasy客戶端身份驗證和HTTP封裝

對於HTTP GET請求這工作正常,我被授權,我得到結果我想要的響應。

但是,如果我想在HTTP請求的HTTP主體中使用Java對象(使用XML)創建HTTP-Post/HTTP-Put,該怎麼辦?有沒有辦法在我使用org.apache.http.impl.client.DefaultHttpClient時自動將Java對象編組爲HTTP對象?

這是我的身份驗證代碼,有人能告訴我如何在不編寫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 


} 

是否有可能使用服務器端的模擬框架,然後馬歇爾和發送我的對象呢?

回答

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

} 

EmployeeResource:

@Path("/employee") 
public interface EmployeeResource { 

    @PUT 
    @Consumes({"application/json", "application/xml"}) 
    void createEmployee(Employee employee); 

} 
+0

喬希您好,請您發表您的MyResourceClass怎麼樣子? –

+0

對不起,延遲迴復。我更新了代碼,向您展示MyResourceClass,現在名爲EmployeeResource! – joshi737