Java httpcomponents发送get post请求代码实例

发布时间:2020-09-28 03:08:01 作者:贾树丙
来源:脚本之家 阅读:203

引入的包为:

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.5.8</version>
</dependency>

实现的工具类为:

import com.alibaba.fastjson.JSON;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpClientHelper {
  private static Logger logger = LoggerFactory.getLogger(HttpClientHelper.class);

  private HttpClientHelper() {

  }

  /**
   * 发起POST请求
   *
   * @param url   url
   * @param paramMap 参数的Map格式
   */
  public static void sendPost(String url, Map<String, String> paramMap) {
    logger.info("开始发起POST请求,请求地址为{},参数为{}", url, JSON.toJSON(paramMap));
    CloseableHttpResponse response = null;

    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
      String encoding = "utf-8";
      //创建post请求对象
      HttpPost httpPost = new HttpPost(url);
      //装填请求参数
      List<NameValuePair> list = new ArrayList<>();
      for (Map.Entry<String, String> entry : paramMap.entrySet()) {
        list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
      }
      //设置参数到请求对象中
      httpPost.setEntity(new UrlEncodedFormEntity(list, encoding));
      httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
      httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
      response = httpClient.execute(httpPost);

    } catch (IOException e) {
      logger.error("POST请求发出失败,请求的地址为{},参数为{},错误信息为{}", url, JSON.toJSON(paramMap), e.getMessage(), e);
    } finally {
      try {
        if (response != null) {
          response.close();
        }
      } catch (IOException e) {
        logger.error("POST请求response关闭异常,错误信息为{}", e.getMessage(), e);
      }
    }
  }

  /**
   * 发起GET请求
   *
   * @param urlParam url请求,包含参数
   */
  public static void sendGet(String urlParam) {
    logger.info("开始发起GET请求,请求地址为{}", urlParam);
    HttpGet httpGet = new HttpGet(urlParam);
    CloseableHttpResponse response = null;
    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
      response = httpClient.execute(httpGet);
      int status = response.getStatusLine().getStatusCode();
      logger.error("GET请求发出成功,请求的地址为{},返回状态为{}", urlParam, status);
    } catch (IOException e) {
      logger.error("GET请求发出失败,请求的地址为{},错误信息为{}", urlParam, e.getMessage(), e);
    } finally {
      try {
        if (response != null) {
          response.close();
        }
      } catch (IOException e) {
        logger.error("GET请求response关闭异常,错误信息为{}", e.getMessage(), e);
      }
    }
  }

  public static void main(String[] args) {
    String url = "https://jiashubing.cn/tencenttest";
    //需要传入的参数
    Map<String, String> map = new HashMap<>();
    map.put("code", "js");
    map.put("day", "0");
    map.put("city", "北京");
    map.put("dfc", "1");
    map.put("charset", "utf-8");
    sendPost(url, map);


    String urlParam = "https://jiashubing.cn/talk/document?fileid=1234ji贾树丙";
    sendGet(urlParam);
  }
}

如果POST请求想要发送Json 格式的数据,只需要修改成这样:

String json = JSON.toJSONString(paramMap);
StringEntity requestEntity = new StringEntity(json, "utf-8");
httpPost.setEntity(requestEntity);

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

推荐阅读:
  1. 好程序员Java教程分享使用HttpClient抓取页面内容
  2. java如何实现响应重定向发送post请求

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java http components

上一篇:磁盘性能 IOPS和吞吐量说明及raid10和raid5性能比较

下一篇:Java多线程通信:交替打印ABAB实例

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》