post方式不能直接将参数拼接在url后,需要使用固定的方式,将参数添加进去
public static JSONObject getTrafficData(String url) throws IOException {
// 创建httpclients对象,可以理解为打开浏览器
CloseableHttpClient httpClient = HttpClients.createDefault();
// 输入网址 发送get请求
HttpPost httpPostForTraffic = new HttpPost("https://baidu.com");
List<NameValuePair> params = new ArrayList<NameValuePair>();
//设置请求地址是:https://baidu.com";
//设置POST方式的请求的参数,有几个加几个
params.add(new BasicNameValuePair("time1","20"));
params.add(new BasicNameValuePair("time2","21"));
//创建表单的Emtity对象,第一个参数是封装好的表单数据,第二个参数是编码
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params,"utf-8");
httpPostForTraffic.setEntity(formEntity);
httpPostForTraffic.setHeader("User-Agent", "xxxx");
httpPostForTraffic.setHeader("Cookie", "xxxx");
// 发送并接收响应结果
JSONObject jsonObject = null;
CloseableHttpResponse response = null;
responseTraffic = httpClient.execute(httpPost);
// 解析响应,获取数据
System.out.println("response.toString():"+response.toString());
if (response.getStatusLine().getStatusCode() == 200) {
// 响应体数据
System.out.println("访问正确");
HttpEntity entity = response.getEntity();
String conut = EntityUtils.toString(entity, "utf8");
//System.out.println("conut"+conut);
jsonObject = JSONObject.parseObject(conut);
String info = jsonObject.getString("info");
System.out.println("info:"+info);
}
// 关闭连接
try {
response.close();
httpClient.close();
} catch (
IOException e) {
//e.printStackTrace();
}
return jsonObject;
}