Java 使用Httpclient获取数据并使用JSON显示
我必须编写一段代码,从url.com/info/{code}检索特定信息(不是全部),并使用json在我安装的服务器上显示这些信息。Java 使用Httpclient获取数据并使用JSON显示,java,json,apache-httpclient-4.x,http-get,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/
这是我到目前为止的代码: 获取信息的类
@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?首先,必须将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;
非常感谢,我会尝试更正代码,如果我还有任何问题,我会回来的。我成功地让程序按我需要的方式运行。