当前位置: 首页 > news >正文

Htpp中web通讯发送post(上传文件)、get请求

一、正常发送post请求

1、引入pom文件

      <dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5</version></dependency>
2、这个是发送至正常的post、get请求 
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;public class HttpClientUtils {private static final Logger logger = LogManager.getLogger(HttpClientUtils.class);//测试方法
//    public static void main(String[] args) throws IOException {
//        String url="htt";
//        String str = "{\"username\":\"111\",\"password\":\"Tx222\"}";
//        HashMap<String, String> map = new HashMap<>();
//        map.put("username", "111");
//        map.put("password", "222");
//     //   System.out.println(post(url,map));
//        System.out.println("===================================");
//        System.out.println(JSONObject.toJSONString(map));
//        System.out.println(post(url,JSONObject.toJSONString(map)));
//    }//data为 JSONObject.toJSONString(map)public static String post(String url, String data) throws IOException {
//        1、创建HttpClient对象HttpClient httpClient = HttpClientBuilder.create().build();
//        2、创建请求方式的实例HttpPost httpPost = new HttpPost(url);
//        3、添加请求参数(设置请求和传输超时时间)RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();httpPost.setConfig(requestConfig);httpPost.setHeader("Accept", "application/json");httpPost.setHeader("Content-Type", "application/json");
//        设置请求参数httpPost.setEntity(new StringEntity(data, "UTF-8"));
//        4、发送Http请求HttpResponse response = httpClient.execute(httpPost);
//        5、获取返回的内容String result = null;int statusCode = response.getStatusLine().getStatusCode();if (200 == statusCode) {result = EntityUtils.toString(response.getEntity());} else {logger.info("请求第三方接口出现错误,状态码为:{}", statusCode);return null;}
//        6、释放资源httpPost.abort();httpClient.getConnectionManager().shutdown();return result;}public static String get(String url,String token) throws IOException {
//        1、创建HttpClient对象HttpClient httpClient = HttpClientBuilder.create().build();
//        2、创建请求方式的实例HttpGet httpGet = new HttpGet(url);
//        3、添加请求参数(设置请求和传输超时时间)RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();httpGet.setConfig(requestConfig);httpGet.setHeader("Accept", "application/json");httpGet.setHeader("Content-Type", "application/json");//无需求可删除tokenhttpGet.setHeader("Authorization","Bearer "+token);
//        4、发送Http请求HttpResponse response = httpClient.execute(httpGet);
//        5、获取返回的内容String result = null;int statusCode = response.getStatusLine().getStatusCode();if (200 == statusCode) {result = EntityUtils.toString(response.getEntity());} else {logger.info("请求第三方接口出现错误,状态码为:{}", statusCode);return null;}
//        6、释放资源httpGet.abort();httpClient.getConnectionManager().shutdown();return result;}}

二、还有文件上传的需求 这个http5的我简单试了几种不会用 直接引用的之前第三方给的对接方法

        <dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpcore</artifactId><version>4.4.9</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpmime</artifactId></dependency>
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;/*** <p>** @author 花鼠大师* @version :1.0* @date 2024/4/12 15:10*/
@Slf4j
public class SendFileUtils {public static String sendMultipartFile(String url, File file) {//获取HttpClientCloseableHttpClient client = getHttpClient();HttpPost httpPost = new HttpPost(url);fillMethod(httpPost,System.currentTimeMillis());// 请求参数配置RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).setConnectionRequestTimeout(10000).build();httpPost.setConfig(requestConfig);String res = "";String fileName = file.getName();//文件名try {MultipartEntityBuilder builder = MultipartEntityBuilder.create();builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);/*** 假设有两个参数需要传输* 参数名:filaName 值 "文件名"* 参数名:file 值:file (该参数值为file对象)*///表单中普通参数builder.addPart("cardName ",new StringBody("来源", ContentType.create("text/plain", Consts.UTF_8)));// 表单中的文件参数 注意,builder.addBinaryBody的第一个参数要写参数名builder.addBinaryBody("card", file, ContentType.create("multipart/form-data",Consts.UTF_8), fileName);//ContentType contentType = ContentType.create("multipart/form-data",Charset.forName("UTF-8")); //此处也是坑,转发出去的filename依然为乱码builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, fileName);HttpEntity entity = builder.build();httpPost.setEntity(entity);HttpResponse response = client.execute(httpPost);// 执行提交if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 返回响应结果res = EntityUtils.toString(response.getEntity(), java.nio.charset.Charset.forName("UTF-8"));}else {res = "响应失败";log.error("响应失败!");}return res;} catch (Exception e) {e.printStackTrace();log.error("调用HttpPost失败!" + e.toString());} finally {if (client != null) {try {client.close();} catch (IOException e) {log.error("关闭HttpPost连接失败!");}}}log.info("数据传输成功!!!!!!!!!!!!!!!!!!!!");return res;}private static CloseableHttpClient getHttpClient(){SSLContext sslContext = null;try {sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {return true;}}).build();} catch (Exception e) {e.printStackTrace();throw new RuntimeException(e);}SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,NoopHostnameVerifier.INSTANCE);CloseableHttpClient client = HttpClientBuilder.create().setSSLSocketFactory(sslConnectionSocketFactory).build();return client;}/*** 添加头文件信息* @param requestBase* @param timestamp*/private static void fillMethod(HttpRequestBase requestBase, long timestamp){//此处为举例,需要添加哪些头部信息自行添加即可//设置时间戳,nginx,underscores_in_headers on;放到http配置里,否则nginx会忽略包含"_"的头信息requestBase.addHeader("timestamp",String.valueOf(timestamp));System.out.println(requestBase.getAllHeaders());}
}

相关文章:

Htpp中web通讯发送post(上传文件)、get请求

一、正常发送post请求 1、引入pom文件 <dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5</version></dependency>2、这个是发送至正常的post、get请求 import org…...

【论文阅读笔记】HunyuanVideo: A Systematic Framework For Large Video Generative Models

HunyuanVideo: A Systematic Framework For Large Video Generative Models 前言引言Overview数据预处理数据过滤数据注释 模型架构设计3D Variational Auto-encoder Designtraininginference 统一的图像和视频生成架构Text encoderModel ScalingImage model scaling lawvideo …...

SpringBoot的事务钩子函数

如果需要在A方法执行完成之后做一个不影响主方法运行的动作B&#xff0c;我们需要判断这个A方法是否存在事务&#xff0c;并且使用异步执行动作B&#xff1b; import org.springframework.transaction.support.TransactionSynchronization; import org.springframework.transa…...

源码安装PHP-7.2.19

源码安装PHP-7.2.19 1.解压 tar -xjvf php-7.2.19.tar.bz2.编译 -prefix安装路径 cd php-7.2.19 ./configure --prefix/home/work/study 成功输出 3.make(构建) makemake testmake installlinux对php操作的一些命令 # 进入到php [rootvdb1 study]# cd php/ [rootvdb1 st…...

UE5制作伤害浮动数字

效果演示&#xff1a; 首先创建一个控件UI 添加画布和文本 文本设置样式 添加伤害浮动动画&#xff0c;根据自己喜好调整&#xff0c;我设置了缩放和不透明度 添加绑定 转到事件图表&#xff0c;事件构造设置动画 创建actor蓝图类 添加widget 获取位置 设置位移 创建一个被击中…...

学习日志024--opencv中处理轮廓的函数

目录 前言​​​​​​​ 一、 梯度处理的sobel算子函数 功能 参数 返回值 代码演示 二、梯度处理拉普拉斯算子 功能 参数 返回值 代码演示 三、Canny算子 功能 参数 返回值 代码演示 四、findContours函数与drawContours函数 功能 参数 返回值 代码演示 …...

(2024年最新)Linux(Ubuntu) 中配置静态IP(包含解决每次重启后配置文件失效问题)

Hello! 亲爱的小伙伴们&#xff0c;大家好呀&#xff08;Smile~&#xff09;&#xff01;我是Huazzi&#xff0c;欢迎观看本篇博客&#xff0c;接下来让我们一起来学习一下Ubuntu 中如何配置静态IP吧&#xff01;祝你有所收获&#xff01; 提前对Linux有所了解的小伙伴应该知道…...

DPDK用户态协议栈-TCP Posix API 2

tcp posix api send发送 ssize_t nsend(int sockfd, const void *buf, size_t len, __attribute__((unused))int flags) {ssize_t length 0;void* hostinfo get_host_fromfd(sockfd);if (hostinfo NULL) {return -1;}struct ln_tcp_stream* stream (struct ln_tcp_stream…...

[IT项目管理]项目时间管理(本章节3w字爆肝)

七.项目时间管理 7.1 项目进度的重要性 为什么要重视项目进度&#xff1a;在项目进行的过程之中会遇到变故。但是不论项目中发生了什么&#xff0c;时间总是在流逝&#xff0c;就可能会导致项目不可以在规定的时间完成。 7.2可能影响项目进度的因素 有员工离职个人的工作方…...

【python因果库实战5】使用银行营销数据集研究营销决策的效果5

目录 接触次数的效应 重新定义治疗变量和潜在混杂因素 更深入地审视干预情景 逆概率加权 标准化 总结及与非因果分析的比较 接触次数的效应 我们现在转而研究当前营销活动中接触次数的数量&#xff08;campaign&#xff09;对积极结果发生率的影响。具体来说&#xff0c;…...

【Qt】QWidget中的常见属性及其功能(二)

目录 六、windowOpacity 例子&#xff1a; 七、cursor 例子&#xff1a; 八、font 九、toolTip 例子&#xff1a; 十、focusPolicy 例子&#xff1a; 十一、styleSheet 计算机中的颜色表示 例子&#xff1a; 六、windowOpacity opacity是不透明度的意思。 用于设…...

9 OOM和JVM退出。OOM后JVM一定会退出吗?

首先我们把两个概念讲清楚 OOM是线程在申请堆内存&#xff0c;发现堆内存空间不足时候抛出的异常。 JVM退出的条件如下&#xff1a; java虚拟机在没有守护线程的时候会退出。守护线程是启动JVM的线程&#xff0c;服务于用户线程。 我们简单说下守护线程的功能: 1.日志的记录…...

学习笔记070——Java中【泛型】和【枚举】

文章目录 1、泛型1.1、为什么要使用泛型&#xff1f;1.2、泛型的应用1.3、泛型通配符1.4、泛型上限和下限1.5、泛型接口 2、枚举 1、泛型 Generics 是指在定义类的时候不指定类中某个信息&#xff08;属性/方法返回值&#xff09;的具体数据类型&#xff0c;而是用一个标识符来…...

【工具变量】碳排放市场交易数据(2013-2023年)

一、时间范围&#xff1a;2013年8月5日到2023年1月13日 二、具体指标&#xff1a; 交易日期 城市名称 交易品种 开盘价 最高价 最低价 成交均价 收盘价 前收盘价 涨跌幅 总成交量 总成交额 …...

【视频生成模型】——Hunyuan-video 论文及代码讲解和实操

&#x1f52e;混元文生视频官网 | &#x1f31f;Github代码仓库 | &#x1f3ac; Demo 体验 | &#x1f4dd;技术报告 | &#x1f60d;Hugging Face 文章目录 论文详解基础介绍数据预处理 &#xff08;Data Pre-processing&#xff09;数据过滤 (Data Filtering)数据标注 (Data…...

基线检查:Windows安全基线.【手动 || 自动】

基线定义 基线通常指配置和管理系统的详细描述&#xff0c;或者说是最低的安全要求&#xff0c;它包括服务和应用程序设置、操作系统组件的配置、权限和权利分配、管理规则等。 基线检查内容 主要包括账号配置安全、口令配置安全、授权配置、日志配置、IP通信配置等方面内容&…...

uniapp跨端适配—条件编译

在uniapp中&#xff0c;跨端适配是通过条件编译实现的。条件编译允许开发者根据不同的平台&#xff08;如iOS、Android、微信小程序、百度小程序等&#xff09;编写不同的代码。这样可以确保每个平台上的应用都能得到最优的性能和用户体验。 以下是uniapp中条件编译的基本语法…...

【Java基础面试题013】Java中静态方法和实例方法的区别是是么?

回答重点 静态方法 使用static关键字修修饰的方法属于类随着类的加载而加载&#xff0c;随着类的卸载而消失可以通过类名直接调用&#xff0c;也可以通过对象调用&#xff0c;但是这种方式不推荐&#xff0c;会混淆意义&#xff0c;也不利于后期维护与扩展 class Example {st…...

C语言入门(一):A + B _ 基础输入输出

前言 本专栏记录C语言入门100例&#xff0c;这是第&#xff08;一&#xff09;例。 目录 一、【例题1】 1、题目描述 2、代码详解 二、【例题2】 1、题目描述 2、代码详解 三、【例题3】 1、题目描述 2、代码详解 四、【例题4】 1、题目描述 2、代码详解 一、【例…...

Vue日历组件FullCalendar使用方法

FullCalendar &#xff08;全日历&#xff09;Vue组件的使用 FullCalendar官方文档地址 FullCalendar日历组件支持Vue React Angular Javascript Vue2的框架示例&#xff1a; npm install --save fullcalendar/core fullcalendar/vue<template><div class"cal…...

大数据学习栈记——Neo4j的安装与使用

本文介绍图数据库Neofj的安装与使用&#xff0c;操作系统&#xff1a;Ubuntu24.04&#xff0c;Neofj版本&#xff1a;2025.04.0。 Apt安装 Neofj可以进行官网安装&#xff1a;Neo4j Deployment Center - Graph Database & Analytics 我这里安装是添加软件源的方法 最新版…...

利用ngx_stream_return_module构建简易 TCP/UDP 响应网关

一、模块概述 ngx_stream_return_module 提供了一个极简的指令&#xff1a; return <value>;在收到客户端连接后&#xff0c;立即将 <value> 写回并关闭连接。<value> 支持内嵌文本和内置变量&#xff08;如 $time_iso8601、$remote_addr 等&#xff09;&a…...

Prompt Tuning、P-Tuning、Prefix Tuning的区别

一、Prompt Tuning、P-Tuning、Prefix Tuning的区别 1. Prompt Tuning(提示调优) 核心思想:固定预训练模型参数,仅学习额外的连续提示向量(通常是嵌入层的一部分)。实现方式:在输入文本前添加可训练的连续向量(软提示),模型只更新这些提示参数。优势:参数量少(仅提…...

C++:std::is_convertible

C++标志库中提供is_convertible,可以测试一种类型是否可以转换为另一只类型: template <class From, class To> struct is_convertible; 使用举例: #include <iostream> #include <string>using namespace std;struct A { }; struct B : A { };int main…...

通过Wrangler CLI在worker中创建数据库和表

官方使用文档&#xff1a;Getting started Cloudflare D1 docs 创建数据库 在命令行中执行完成之后&#xff0c;会在本地和远程创建数据库&#xff1a; npx wranglerlatest d1 create prod-d1-tutorial 在cf中就可以看到数据库&#xff1a; 现在&#xff0c;您的Cloudfla…...

2025盘古石杯决赛【手机取证】

前言 第三届盘古石杯国际电子数据取证大赛决赛 最后一题没有解出来&#xff0c;实在找不到&#xff0c;希望有大佬教一下我。 还有就会议时间&#xff0c;我感觉不是图片时间&#xff0c;因为在电脑看到是其他时间用老会议系统开的会。 手机取证 1、分析鸿蒙手机检材&#x…...

JVM虚拟机:内存结构、垃圾回收、性能优化

1、JVM虚拟机的简介 Java 虚拟机(Java Virtual Machine 简称:JVM)是运行所有 Java 程序的抽象计算机,是 Java 语言的运行环境,实现了 Java 程序的跨平台特性。JVM 屏蔽了与具体操作系统平台相关的信息,使得 Java 程序只需生成在 JVM 上运行的目标代码(字节码),就可以…...

Mysql中select查询语句的执行过程

目录 1、介绍 1.1、组件介绍 1.2、Sql执行顺序 2、执行流程 2.1. 连接与认证 2.2. 查询缓存 2.3. 语法解析&#xff08;Parser&#xff09; 2.4、执行sql 1. 预处理&#xff08;Preprocessor&#xff09; 2. 查询优化器&#xff08;Optimizer&#xff09; 3. 执行器…...

C++.OpenGL (20/64)混合(Blending)

混合(Blending) 透明效果核心原理 #mermaid-svg-SWG0UzVfJms7Sm3e {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-SWG0UzVfJms7Sm3e .error-icon{fill:#552222;}#mermaid-svg-SWG0UzVfJms7Sm3e .error-text{fill…...

计算机基础知识解析:从应用到架构的全面拆解

目录 前言 1、 计算机的应用领域&#xff1a;无处不在的数字助手 2、 计算机的进化史&#xff1a;从算盘到量子计算 3、计算机的分类&#xff1a;不止 “台式机和笔记本” 4、计算机的组件&#xff1a;硬件与软件的协同 4.1 硬件&#xff1a;五大核心部件 4.2 软件&#…...