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

Getting data with Httpclient and displaying it with JSON

我必须编写一个代码来从 url.com/info/{CODE} 中检索特定信息(不是全部)并使用 json 在服务器中显示它我起来了。
到目前为止,这是我的代码:

A class 获取信息

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

和一个 class 应该 return 数据取决于用户在 url 中插入的代码

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

}

如何为 return 实施 json?

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

如果您检索的数据已经是 json 格式,您可以 return 将其作为字符串。

你的大错:现在你return正在创建一个CloseableHttpResponse类型的对象。将 generate() 的 return 类型从 CloseableHttpResponse 更改为 String 和 return 字符串。

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;