当前位置: 首页 > 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());}
}
http://www.lryc.cn/news/505454.html

相关文章:

  • 【论文阅读笔记】HunyuanVideo: A Systematic Framework For Large Video Generative Models
  • SpringBoot的事务钩子函数
  • 源码安装PHP-7.2.19
  • UE5制作伤害浮动数字
  • 学习日志024--opencv中处理轮廓的函数
  • (2024年最新)Linux(Ubuntu) 中配置静态IP(包含解决每次重启后配置文件失效问题)
  • DPDK用户态协议栈-TCP Posix API 2
  • [IT项目管理]项目时间管理(本章节3w字爆肝)
  • 【python因果库实战5】使用银行营销数据集研究营销决策的效果5
  • 【Qt】QWidget中的常见属性及其功能(二)
  • 9 OOM和JVM退出。OOM后JVM一定会退出吗?
  • 学习笔记070——Java中【泛型】和【枚举】
  • 【工具变量】碳排放市场交易数据(2013-2023年)
  • 【视频生成模型】——Hunyuan-video 论文及代码讲解和实操
  • 基线检查:Windows安全基线.【手动 || 自动】
  • uniapp跨端适配—条件编译
  • 【Java基础面试题013】Java中静态方法和实例方法的区别是是么?
  • C语言入门(一):A + B _ 基础输入输出
  • Vue日历组件FullCalendar使用方法
  • TinyML在OBD-II边缘设备上燃油类型分类的实现与优化
  • vue3 中 defineProps 声明示例
  • SpringBoot整合MybatisPlus报错Bean不存在:NoSuchBeanDefinitionException
  • 异步电机的控制是否还有研究的必要,是不是已经非常成熟了?
  • 【Android】解决 ADB 中 SELinux 设置与 `Failed transaction (2147483646)` 错误
  • 企业车辆管理系统(源码+数据库+报告)
  • SAP RESTful架构和OData协议
  • centOS定时任务-cron服务
  • Python毕业设计选题:基于django+vue的宠物服务管理系统
  • css常用属性有哪些
  • 八大设计模式