2016-04-30 81 views
0

這是一個Spring應用程序,我試圖做一個POST請求並獲取響應。如何從POST請求獲取響應對象?

在服務器端我有這個

@CrossOrigin 
@RequestMapping(value = "/test", method = RequestMethod.POST) 
public 
@ResponseBody 
Test testmethod(@RequestBody Test test) { 
    test.setValue("test"); 
return test; 
} 

在客戶端我有POST方法應該返回測試對象。我使用JSON進行編碼。

public Object post(String url1, Test test) throws IOException, ClassNotFoundException { 

    ObjectMapper mapper = new ObjectMapper(); 
    String jsonInString = mapper.writeValueAsString(login); 

    try { 

     DefaultHttpClient httpClient = new DefaultHttpClient(); 
     HttpPost postRequest = new HttpPost(url1); 

     StringEntity input = new StringEntity(jsonInString); 
     input.setContentType("application/json"); 
     postRequest.setEntity(input); 

     HttpResponse response = httpClient.execute(postRequest); 

     //read the object from the response, how to do that? 
     //responseObject = ????? 

     httpClient.getConnectionManager().shutdown(); 

    } catch (MalformedURLException e) { 

     e.printStackTrace(); 

    } catch (IOException e) { 

     e.printStackTrace(); 

    } 
return responseObject; 
} 

而且

Test s = new Test; 
Test s=(Test)post("http://localhost:8081/basic-web-app/test",s); 

我的問題是,我不知道燙得到響應測試對象。請幫忙。謝謝!

回答

0

你可以嘗試使用:

String responseAsString = EntityUtils.toString(response.getEntity()); 
+0

但我並不需要一個字符串,需要一個測試對象。 – mlhack

+0

你發送json,所以它是一個字符串。只需使用一些JSON到Object轉換器 – mariusz2108

相關問題