2015-08-29 34 views
2

我必須編寫一個代碼,它從url.com/info/{CODE}獲取特定信息(並非全部),並使用json將其顯示在服務器中。
這是我的代碼到現在爲止:使用Httpclient獲取數據並使用JSON顯示

一個類來獲取信息

@RequestMapping("/info") 
public class Controller { 

    public void httpGET() throws ClientProtocolException, IOException { 

     String url = "Getfromhere.com/"; 

     CloseableHttpClient client = HttpClients.createDefault(); 
     HttpGet request = new HttpGet(url); 
     CloseableHttpResponse response = client.execute(request); 
    } 

和一類應返回根據用戶在URL中插入的代碼數據

@RequestMapping(value = "/{iataCode}", method = RequestMethod.GET) 
@ResponseBody 
public CloseableHttpResponse generate(@PathVariable String iataCode) { 
    ; 
    return response; 

} 

我該如何實現json的返回?

回答

2

首先,您必須將Spring配置爲使用Jackson或其他API將所有響應轉換爲json。

如果您要檢索的數據已經是json格式,則可以將其作爲字符串返回。

你的大錯誤:現在你正在返回一個CloseableHttpResponse類型的對象。將返回類型的generate()從CloseableHttpResponse更改爲String並返回一個字符串。

CloseableHttpResponse response = client.execute(request); 

String res = null; 

HttpEntity entity = response.getEntity(); 

if (entity != null) { 

    InputStream instream = entity.getContent(); 

    byte[] bytes = IOUtils.toByteArray(instream); 

    res = new String(bytes, "UTF-8"); 

    instream.close(); 

} 

return res; 
+0

多謝,我會盡力糾正代碼,我會回來,如果我有任何更多的問題 – langStrife

+0

它的工作,我設法運行,我需要的方式,程序。 – langStrife