创建Get请求
HttpGet httpGet = new HttpGet(url+param);
设置请求头信息
HttpGet httpGet = new HttpGet(url+param); httpGet.setHeader("Token",token); httpGet.setHeader("Timespan",time);
设置响应模型
CloseableHttpResponse response = null;
客户端发起请求:这里要处理异常,调用的是响应模型的变量
//客户端发起请求 response = httpClient.execute(httpGet);
获取实体
//从相应模型中获取实体 HttpEntity responseEntity = response.getEntity();
方法:
getContentLength() 获取响应内容长度
EntityUtils.toString(responseEntity) 获取响应内容
完整代码
public static void main(String[] args) {/** * 请求头 * @param Token 验证加密值 Md5(key+Timespan+SecretKey) 加密的32位大写字符串) * @param Timespan 精确到秒的Unix时间戳 * 请求参数 * @param key 应用APPKEY(应用详细页查询) * @param keyword 搜索关键字 */ LocalDateTime time = LocalDateTime.now(); String Timespan = time.toString(); String Token = MD5Util.toMD5(appkey+Timespan+secretKey); String url = "http://api.qichacha.com/ECIV4/SearchWide?key="+ secretKey + "keyword=零瓴软件"; // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的) CloseableHttpClient httpClient = HttpClientBuilder.create().build(); // 创建Get请求 HttpGet httpGet = new HttpGet(url); // 添加请求头信息 httpGet.addHeader("Token",Token); httpGet.addHeader("Timespan",Timespan); // 响应模型 CloseableHttpResponse response = null; try { // 由客户端执行(发送)Get请求 response = httpClient.execute(httpGet); // 从响应模型中获取响应实体 HttpEntity responseEntity = response.getEntity(); System.out.println("响应状态为:" + response.getStatusLine()); if (responseEntity != null) { System.out.println("响应内容长度为:" + responseEntity.getContentLength()); System.out.println("响应内容为:" + EntityUtils.toString(responseEntity)); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { // 释放资源 if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } }
欢迎关注作者微信公众号