//发送get请求,参数和url分开
public static Map<String, Object> sendGet_params(String url, String[] name, String[] value, String[] herderName, String[] headerValue) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
//添加传参
List<NameValuePair> params = new ArrayList<>();
for (int i = 0; i < name.length; i++) {
BasicNameValuePair basicNameValuePair = new BasicNameValuePair(name[i].trim(), value[i].trim());//trim():去掉字符串首尾的空格
params.add(basicNameValuePair);
}
String str = EntityUtils.toString(new UrlEncodedFormEntity(params, Consts.UTF_8));//转换为键值对
HttpGet httpGet = new HttpGet(url + "?" + str); //创建Get请求
// 设置超时
httpGet.setConfig(requestConfig);
//添加herder信息
for (int i = 0; i < herderName.length; i++) {
httpGet.addHeader(herderName[i], headerValue[i]);
}
LocalTime startTime = LocalTime.now();//响应开始时间
CloseableHttpResponse response = httpClient.execute(httpGet);//执行Get请求
LocalTime endTime = LocalTime.now();//响应结束时间
int code = response.getStatusLine().getStatusCode();
if (code != 200) {
System.out.println(url + response);
}
Map<String, Object> map = new HashMap<>();
map.put("entity", EntityUtils.toString(response.getEntity(), "utf-8"));//得到响应体
map.put("Content-Type", response.getEntity().getContentType().getValue());
map.put("code", code);
map.put("responseTime", Duration.between(startTime, endTime).toMillis());
response.close();
httpClient.close();
return map;
}
//发送get请求,一整个url
public static Map<String, Object> sendGet(String url, String[] herderName, String[] headerValue) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
// 设置超时
httpGet.setConfig(requestConfig);
//添加herder信息
for (int i = 0; i < herderName.length; i++) {
httpGet.addHeader(herderName[i], headerValue[i]);
}
LocalTime startTime = LocalTime.now();//响应开始时间
CloseableHttpResponse response = httpClient.execute(httpGet);
LocalTime endTime = LocalTime.now();//响应结束时间
int code = response.getStatusLine().getStatusCode();
if (code != 200) {
System.out.println(url + response);
}
Map<String, Object> map = new HashMap<>();
map.put("entity", EntityUtils.toString(response.getEntity(), "utf-8"));
map.put("Content-Type", response.getEntity().getContentType().getValue());
map.put("code", code);
map.put("responseTime", Duration.between(startTime, endTime).toMillis());
response.close();
httpClient.close();
return map;
}
|