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

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");
        //无需求可删除token
        httpGet.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) {
        //获取HttpClient
        CloseableHttpClient 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.kler.cn/a/441030.html

相关文章:

  • openssl 生成证书 windows导入证书
  • 大数据学习之Kafka消息队列、Spark分布式计算框架一
  • Linux《基础指令》
  • 单细胞-第五节 多样本数据分析,打分R包AUCell
  • S4 HANA明确税金本币和外币之间转换汇率确定(OBC8)
  • 房屋租赁系统在数字化时代中如何重塑租赁服务与提升市场竞争力
  • 深度学习——激活函数、损失函数、优化器
  • SQL 中的 JOIN(JOIN 简化与提速系列 1)
  • CS 144 check2: the TCP receiver
  • 算法杂记(算法学习)
  • 华为ensp--BGP路径选择-Preferred Value
  • 【WRF教程第二期】WRF编译全过程:以4.5版本为例
  • 好用的工单系统,适用于各种场景
  • Python金融大数据分析快速入门与案例详解
  • ArkTs的容器布局
  • GitHub 开源仓库推荐:poe2skills
  • LLaMA-Factory QuickStart 流程详解
  • 大屏开源项目go-view二次开发3----象形柱图控件(C#)
  • OCR:文字识别
  • 【深度学习】深入解析生成对抗网络(GAN)
  • 从零开始学Java,学习笔记Day23
  • 卓易通:鸿蒙Next系统的蜜糖还是毒药?
  • CSS边框和圆角边框
  • Codeforces Global Round 27的C题
  • 构建高性能异步任务引擎:FastAPI + Celery + Redis
  • 33. Three.js案例-创建带阴影的球体与平面