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

server/2024/12/19 4:32:58/

一、正常发送post请求

1、引入pom文件

      <dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5</version></dependency>
2、这个是发送至正常的postget请求 
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());}
}

http://www.ppmy.cn/server/151355.html

相关文章

LVGL9.2 鼠标悬停处理

文章目录 前言鼠标悬停处理功能简介使用场景1. **按钮悬停效果**2. **图标高亮**3. **动态工具提示** 实现原理使用方法1. 设置控件样式2. 监听悬停事件 功能亮点注意事项总结 前言 在 v9.2 版本中&#xff0c;新增了许多功能&#xff0c;其中鼠标悬停处理&#xff08;Mouse H…

React 基础:剖析 UI 描述之道

目录 介绍编写你的第一个组件定义组件使用组件组件的导入与导出 使用JSX代替HTMLJSX规则JSX中通过大括号使用JS 将 Props 传递给组件向组件传递props使用 JSX 展开语法传递 props将JSX作为子组件传递 条件渲染条件返回JSX三目运算符与运算符 渲染列表对数组进行过滤并渲染数据用…

Linux高性能服务器编程中的TCP带外数据梳理总结

Linux高性能服务器编程中的TCP带外数据梳理总结 文章目录 Linux高性能服务器编程中的TCP带外数据梳理总结1.TCP 带外数据总结2.第五章带外数据send.crecv.c 3.第九章带外数据send.cselect.c 4.第十章带外数据send.csig_msg.c 1.TCP 带外数据总结 至此&#xff0c;我们讨论完了…

RPM(Red Hat Package Manager)的功能解析

RPM 是一种用于 Linux 系统的软件包管理器&#xff0c;主要用于安装、升级、查询、验证、卸载和管理软件包。 1. RPM 的基本功能 1.1 软件包安装 安装新软件包。安装时会自动检查依赖关系&#xff0c;提示需要的依赖。命令&#xff1a; rpm -ivh package.rpm参数说明&#xf…

docker xxxx is using its referenced image ea06665f255d

Error response from daemon: conflict: unable to remove repository reference “registrxxxxxx” (must force) - container 9642fd1fd4a0 is using its referenced image ea06665f255d 这个错误表明你尝试删除的镜像正在被一个容器使用&#xff0c;因此无法删除。要解决这…

基于SpringBoot的乡村信息服务平台的设计与实现

摘 要 乡村信息服务平台的研究背景源于当前乡村振兴战略的实施和信息化技术的快速发展。随着城乡经济差距的逐渐凸显&#xff0c;乡村信息服务平台成为一种新型的信息化手段。本系统采用Java语言&#xff0c;MySQL数据库&#xff0c;采用MVC框架, JS技术开发。乡村信息服务平…

秒杀业务中的库存扣减为什么不加分布式锁?

前言 说到秒杀业务的库存扣减&#xff0c;就还是得先确认我们的扣减基本方案。 秒杀场景的库存扣减方案 一般的做法是&#xff0c;先在Redis中做扣减&#xff0c;然后发送一个MQ消息&#xff0c;消费者在接到消息之后做数据库中库存的真正扣减及业务逻辑操作。 如何解决数据…

定时/延时任务-Kafka时间轮源码分析

文章目录 1. 概要2. TimingWheel2.1 核心参数2.2 添加任务2.3 推进时间 3. TimerTaskList3.1 添加节点3.2 删除节点3.3 刷新链表3.4 队列相关 4. 时间轮链表节点-TimerTaskEntry5. TimerTask6. Timer 和 SystemTimer - 设计降级逻辑7. 上层调用8. 小结 1. 概要 时间轮的文章&a…