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

 更新时间:2020年09月17日 11:05:10   作者:贾树丙  
这篇文章主要介绍了Java httpcomponents发送get post请求代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

引入的包为:

<!-- 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);

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

相关文章

  • Java中的关键字volatile详解

    Java中的关键字volatile详解

    这篇文章主要介绍了Java中的关键字volatile,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-03-03
  • Java图片压缩三种高效压缩方案详细解析

    Java图片压缩三种高效压缩方案详细解析

    图片压缩通常涉及减少图片的尺寸缩放、调整图片的质量(针对JPEG、PNG等)、使用特定的算法来减少图片的数据量等,这篇文章主要介绍了Java图片压缩三种高效压缩方案的相关资料,需要的朋友可以参考下
    2025-04-04
  • springboot打成jar后获取classpath下文件失败的解决方案

    springboot打成jar后获取classpath下文件失败的解决方案

    这篇文章主要介绍了使用springboot打成jar后获取classpath下文件失败的解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-08-08
  • Java面向对象之抽象类,接口的那些事

    Java面向对象之抽象类,接口的那些事

    这篇文章主要介绍了Java面向对象基础:抽象类和接口,文中代码可以帮助各位更好的理解学习,有需求的小伙伴可以参考下,希望能够给你带来帮助
    2021-08-08
  • idea报错:java程序包com.github.xiaoymin.knife4j.spring.annotations不存在问题解决

    idea报错:java程序包com.github.xiaoymin.knife4j.spring.annotations

    这篇文章主要介绍了idea报错:java程序包com.github.xiaoymin.knife4j.spring.annotations不存在问题解决,需要的朋友可以参考下
    2023-06-06
  • Java的作业调度类库Quartz基本使用指南

    Java的作业调度类库Quartz基本使用指南

    这篇文章主要介绍了Java的作业调度类库Quartz基本使用指南,Quartz能够让类按照指定的计划顺序执行,需要的朋友可以参考下
    2016-03-03
  • springboot+springsecurity如何实现动态url细粒度权限认证

    springboot+springsecurity如何实现动态url细粒度权限认证

    这篇文章主要介绍了springboot+springsecurity如何实现动态url细粒度权限认证的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-06-06
  • java的list集合排序自定义元素方式

    java的list集合排序自定义元素方式

    在Java中,对包含自定义元素的List集合进行排序可以使用Collections.sort()方法,并结合自定义的比较器实现,以Student类为例,通过实现Comparator接口来按学生年龄升序排序
    2024-12-12
  • Java数据结构之链表详解

    Java数据结构之链表详解

    本篇文章我们将讲解一种新型的数据结构—链表,链表是一种使用广泛的通用数据结构,它可以用来作为实现栈,队列等数据结构的基础.文中有非常详细的介绍,需要的朋友可以参考下
    2021-05-05
  • Spring基于注解管理bean实现方式讲解

    Spring基于注解管理bean实现方式讲解

    很多时候我们需要根据不同的条件在容器中加载不同的Bean,或者根据不同的条件来选择是否在容器中加载某个Bean,这就是Bean的加载控制,一般我们可以通过编程式或注解式两种不同的方式来完成Bean的管理
    2023-01-01

最新评论