2015-08-29 85 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