使用Httpclient获取数据并使用JSON显示它

时间:2015-08-29 20:34:05

标签: java json apache-httpclient-4.x http-get

我必须编写一个代码,从url.com/info/{CODE}检索特定信息(不是全部),并使用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);
    }

和一个应该根据用户在网址中插入的代码返回数据的类

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

}

如何为返回实现json?。

1 个答案:

答案 0 :(得分:2)

首先,您必须配置Spring以使用Jackson或其他API将您的所有响应转换为json。

如果要检索的数据已经是json格式,则可以将其作为String返回。

你的大错:现在你要返回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;