Springboot封装好的发送http请求的工具类代码(最下面有普通的工具类):

  public static Response sendPostRequest(String url, Map<String, Object> params){RestTemplate client = new RestTemplate();HttpHeaders headers = new HttpHeaders();HttpMethod method = HttpMethod.POST;// 以什么方式提交,自行选择,一般使用json,或者表单headers.setContentType(MediaType.APPLICATION_JSON_UTF8);//将请求头部和参数合成一个请求HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(params, headers);//执行HTTP请求,将返回的结构使用Response类格式化ResponseEntity<Response> response = client.exchange(url, method, requestEntity, Response.class);return response.getBody();}

再附带一个我使用的Response类

/*** @author peter* @version 1.0* @title Response*/
public class Response<T> implements Serializable {public void setSuccess(boolean success) {this.success = success;}private boolean success;private T result;private String errorCode;private String errorMsg;public Response() {}public Response(T result) {this.success = true;this.result = result;}public Response(boolean flag, T result) {if (flag) {this.success = true;this.result = result;} else {this.success = false;this.errorCode = (String) result;}}public Response(String errorCode) {this.success = false;this.errorCode = errorCode;}public Response(String errorCode, String errorMsg) {this.success = false;this.errorCode = errorCode;this.errorMsg = errorMsg;}public boolean isSuccess() {return this.success;}public T getResult() {return this.result;}public void setResult(T result) {this.success = true;this.result = result;}public String getErrorCode() {return this.errorCode;}public void setErrorCode(String errorCode) {this.success = false;this.errorCode = errorCode;}public String getErrorMsg() {return this.errorMsg;}public void setErrorMsg(String errorMsg) {this.errorMsg = errorMsg;}@Overridepublic boolean equals(Object o) {if (this == o) {return true;} else if (o != null && this.getClass() == o.getClass()) {Response response = (Response) o;boolean isErrorCode = !this.errorCode.equals(response.errorCode) ? false : this.result.equals(response.result);return this.success != response.success ? false : (isErrorCode);} else {return false;}}@Overridepublic int hashCode() {int result1 = this.success ? 1 : 0;result1 = 31 * result1 + this.result.hashCode();result1 = 31 * result1 + this.errorCode.hashCode();return result1;}@Overridepublic String toString() {return "Response{" +"success=" + success +", result=" + result +", errorCode='" + errorCode + '\'' +", errorMsg='" + errorMsg + '\'' +'}';}
}

普通的发送http请求的工具类:

import com.zhang.railway.common.Response;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;public class HttpUtil {/*** 向指定URL发送GET方法的请求** @param url*            发送请求的URL* @param* @return URL 所代表远程资源的响应结果*/public static String sendGet(String url) {String result = "";BufferedReader in = null;try {URL realUrl = new URL(url);// 打开和URL之间的连接URLConnection connection = realUrl.openConnection();// 设置通用的请求属性connection.setRequestProperty("Content-Type","application/json");connection.setRequestProperty("accept", "*/*");connection.setRequestProperty("connection", "Keep-Alive");connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");// 建立实际的连接connection.connect();// 获取所有响应头字段Map<String, List<String>> map = connection.getHeaderFields();// 遍历所有的响应头字段
//            for (String key : map.keySet()) {
//                System.out.println(key + "--->" + map.get(key));
//            }// 定义 BufferedReader输入流来读取URL的响应in = new BufferedReader(new InputStreamReader(connection.getInputStream()));String line;while ((line = in.readLine()) != null) {result += line;}} catch (Exception e) {System.out.println("发送GET请求出现异常!" + e);e.printStackTrace();}// 使用finally块来关闭输入流finally {try {if (in != null) {in.close();}} catch (Exception e2) {e2.printStackTrace();}}return result;}/*** 向指定 URL 发送POST方法的请求** @param url*            发送请求的 URL* @param param*            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。* @return 所代表远程资源的响应结果*/public static String sendPost(String url, String param) {PrintWriter out = null;BufferedReader in = null;String result = "";try {URL realUrl = new URL(url);// 打开和URL之间的连接URLConnection conn = realUrl.openConnection();// 设置通用的请求属性conn.setRequestProperty("accept", "*/*");conn.setRequestProperty("connection", "Keep-Alive");conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");// 发送POST请求必须设置如下两行conn.setDoOutput(true);conn.setDoInput(true);// 获取URLConnection对象对应的输出流out = new PrintWriter(conn.getOutputStream());// 发送请求参数out.print(param);// flush输出流的缓冲out.flush();// 定义BufferedReader输入流来读取URL的响应in = new BufferedReader(new InputStreamReader(conn.getInputStream()));String line;while ((line = in.readLine()) != null) {result += line;}} catch (Exception e) {System.out.println("发送 POST 请求出现异常!"+e);e.printStackTrace();}//使用finally块来关闭输出流、输入流finally{try{if(out!=null){out.close();}if(in!=null){in.close();}}catch(IOException ex){ex.printStackTrace();}}return result;}
}

Springboot封装的好的发送post请求的工具类相关推荐

  1. JavaSocket编写发送TCP请求的工具类

    转自:https://blog.csdn.net/jadyer/article/details/8788303 package com.jadyer.util;import java.io.ByteA ...

  2. 分享一个发送http请求的工具类

    分享一个发送http请求的工具类 maven依赖只需要导入一个 <dependencies><dependency><groupId>commons-httpcli ...

  3. Objective-c 异步发送Post请求的工具类

    原文链接iOS开发--post异步网络请求封装 有改动 HttpUtil.h #import <Foundation/Foundation.h> #import <UIKit/UIK ...

  4. 发送http请求的工具类

    大家工作中都会遇到使用http请求调用合作商接口的需求,下面分享一个封装好的http请求工具类 1.发送GET请求 /***发送GET方法的请求*/public static String sendG ...

  5. 超好用的后端发送http请求HttpUtils工具类(基于原生http连接,不需要另外导包)

    在项目中,为了实现一些特定的功能,我们常常需要发送http异步请求 ,为此需要特意封装一个实用的HttpUtils工具类 HttpUtils工具类内容如下: package com.zyw.secki ...

  6. 【短信发送】实现腾讯云发送短信功能--工具类和SpringBoot配置两种方法实现

    实现腾讯云发送短信功能--工具类和SpringBoot配置两种方法实现 一.开通腾讯云短信服务 二.工具类--使用qcloudsms实现短信发送 三.Spring Boot项目引入短信发送功能 我们发 ...

  7. java常用的发送http请求的工具方法

    java常用的HttpURLConnection 方式发送http请求的工具方法 需要的jar包有jsp-api.jar .servlet-api.jar .dom4j.jar package cn. ...

  8. 前端请求接口post_程序员:HttpClient进行post请求的工具类,访问第三方接口HTTPS...

    HTTPS (英语:Hypertext Transfer Protocol Secure,缩写:HTTPS,常称为HTTP over TLS,HTTP over SSL或HTTP Secure) 是一 ...

  9. Http请求-hutool工具类的使用

    Http请求-hutool工具类的使用 前言 在日常java后端开发的工作中经常会遇到后端发起HTTP请求的情况,这里可以使用一个简单的工具类. 官方网址:Http请求-HttpRequest (hu ...

  10. Java利用反射封装DBUtil,mysql万能增删改查工具类,附源码

    Java利用反射封装DBUtil,mysql万能增删改查工具类,附源码 等有时间再慢慢写代码注释吧,先把源码放出来.文章最后有整个项目的压缩包. ps:拓展 Java 原生MySQL JDBC 插入后 ...

最新文章

  1. ASP.NET中实现大结果集分页研讨 转
  2. 计算机课程成绩表排名怎么算,微机原课程设计学生成绩名次表设计.doc
  3. 通过Lazada成功打造自主女包品牌,这2个大学生是怎么做到的?
  4. 如何使Mac Docker支持SQL on Linux容器Volume特性
  5. shell 脚本 自动化
  6. 绿色版本Tomcat
  7. 首提 Database Plus 新理念,SphereEx 获数百万美元天使融资,接棒 ShardingSphere 打造新型分布式生态
  8. 使用Keil5构建GD32450i-EVAL工程
  9. Unity3D中脚本的执行顺序和编译顺序
  10. 【物理应用】基于matlab GUI工程供配电系统【含Matlab源码 1051期】
  11. 通过斐波那契数列探讨时间复杂度和空间复杂度
  12. 孩子教育,不要只看重分数!
  13. h5锁屏提醒-锁横屏和锁竖屏
  14. python之seed()函数
  15. win10电脑安装Photoshop cs7软件版本
  16. Window下python安装metis
  17. JAVA基础学习-复习day11
  18. Cuckoo安装指南(二)
  19. 美食网站php模板,红色大气美食餐饮网站模板
  20. 2023系统分析师---冲刺高频错题

热门文章

  1. matlab在图像两点连线,matlab画图,画出任意两点间的连线图,请高人帮忙呀,谢谢!谢谢!...
  2. 软件架构师的12项修炼——关系技能修炼(2)
  3. Linux常用软件包(常用命令)
  4. Spark 已死,Storm 已凉,Flink 永远滴神!
  5. html自动弹出公告代码,可定时自动关闭的弹出层广告窗口代码
  6. php 百度地图 云存储,jspopular3.0 | 百度地图API SDK
  7. ubuntu 1604 安装 rabbitvcs
  8. 卡巴斯基正式版 送一年
  9. JAVA idea中安装P3C方法和使用指南
  10. CTPN - 自然场景文本检测