java用org.apache.http.client.HttpClient发送get请求(参数和url分开、一整个url)

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 21:02   4891   0
//发送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;
}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP