SpringBoot简单使用Http和Https发送请求


SpringBoot简单使用Http和Https发送请求


声明:本人也是从网上的大神中学习来的,写下来就是为了以后自己好找回


1. HTTP–post/get请求,带文件post请求


package com.cly.utils.Http.http;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * @author : CLy
 * @ClassName : httpQuery
 * @date : 2020/7/8 17:04
 **/
public class httpQuery {
    //日志输出
    private static Logger logger = LoggerFactory.getLogger(httpQuery.class);
    /**HTTP
     * psot请求
     * 以String格式返回响应体
     * url:请求路径
     * param :请求参数(可为空)
     * header:请求头部数据(可为空)
     * */
    public  String httpPost(String url,Map<String,String> param,Map<String,String> header) throws IOException {
        //声明一个Http客户端,类似新开一个postman的一个请求界面
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        //创建Post请求
        HttpPost httpPost = new HttpPost(url);//将请求路径写入post请求
        //设置请求头部信息
        for (Map.Entry<String, String> entry : header.entrySet()) {
            httpPost.setHeader(entry.getKey(),entry.getValue());
            //httpPost.setHeader("Content-Type", "application/json;charset=utf8");
            //httpPost.setHeader("请求头部参数名", "请求头部参数值");
        }
        //声明一个请求body
        ByteArrayEntity entity = null;
        try {
            if (param.size()>0){
                JSON json = (JSON) JSON.toJSON(param);//用fastJson数据将map转成json
                String requestBody = json.toJSONString();//json转成string
                entity = new ByteArrayEntity(requestBody.getBytes("UTF-8"));//数据以byte格式写入body
                entity.setContentType("application/json");//设置body格式为json
            }
        } catch (UnsupportedEncodingException e) {
            logger.warn("请求body封装异常!");
            throw new RuntimeException("请求body封装异常!", e);
        }
        httpPost.setEntity(entity);//将body写入post请求
        //声明response响应模型
        CloseableHttpResponse response = null;
        //声明返回的response中的实体
        HttpEntity responseEntity = null;
        try {
            //客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);
            //从response响应模型中获取响应实体
            responseEntity = response.getEntity();
            //logger.info("响应状态为:" + response.getStatusLine());
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {  // 释放所有资源
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return EntityUtils.toString(responseEntity);//将HttpEntity响应实体转成String返回
    }


    /**HTTP
    * get请求
    * 以String格式返回响应体
    * url:请求路径
    * param:请求参数(可为空)
    * header:请求头部数据(可为空)
    * */
    public String httpGet(String url,Map<String,String> param,Map<String,String> header) throws IOException {
        //声明一个Http客户端,类似新开一个postman的一个请求界面
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        //创建url
        String getUrl = null;
        if(param.size()>0){//将请求参数和路径拼接生成完整的请求路径
            String data = "";
            for(Map.Entry<String,String> map :param.entrySet()){
                data=data+"&"+map.getKey()+"="+map.getValue();
            }
            getUrl=url+"?"+data.substring(1);
        }else {
            getUrl = url;
        }
        //创建get请求
        HttpGet httpGet = new HttpGet(getUrl);
        //设置请求头部信息
        for (Map.Entry<String, String> entry : header.entrySet()) {
            httpGet.setHeader(entry.getKey(),entry.getValue());
            //httpGet.setHeader("Content-Type", "application/json;charset=utf8");
            //httpGet.setHeader("请求头部参数名", "请求头部参数值");
        }
        //声明response响应模型
        CloseableHttpResponse response = null;
        //声明接口返回的response中的响应实体
        HttpEntity responseEntity = null;
        try {
            //由客户端执行(发送)Post请求
            response = httpClient.execute(httpGet);
            //从response响应模型中获取响应实体
            responseEntity = response.getEntity();
            logger.info("响应状态为:" + response.getStatusLine());
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally { //释放全部资源
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return EntityUtils.toString(responseEntity);//将HttpEntity响应实体转成String返回
    }

    /**HTTP
     * 带文件psot请求
     * 以String格式返回响应体
     * url:请求路径
     * file : 请求文件
     * param :请求参数(可为空)
     * header:请求头部数据(可为空)
     * */
    public  static  String  httpPostWithFile(String url,File file,Map<String,String> param,Map<String,String> header) throws IOException {
        //声明一个Http客户端,类似新开一个postman的一个请求界面
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        //创建Post请求
        HttpPost httpPost = new HttpPost(url);
        //设置请求头部信息
        for (Map.Entry<String, String> entry : header.entrySet()) {
            httpPost.setHeader(entry.getKey(),entry.getValue());
            //httpPost.setHeader("Content-Type", "application/json;charset=utf8");
            //httpPost.setHeader("请求头部参数名", "请求头部参数值");
        }
        //设置超时
        //RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000000).build();
        //httpPost.setConfig(requestConfig);
        //声明一个Multipart构造器
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        //向MultipartEntityBuilder添加文件,参数名为file,可自定义
        multipartEntityBuilder.addBinaryBody("file",file);
        //multipartEntityBuilder.addBinaryBody("file2",file2);//可多个文件,还有其他添加文件方式,详细可查看MultipartEntityBuilder的构造方法
        //添加请求其他文本参数
        if (param.size()!=0){
            for (Map.Entry<String, String> entry : param.entrySet()) {
                    multipartEntityBuilder.addTextBody(entry.getKey(),entry.getValue());
            }
        }
        //由MultipartEntityBuilder构建成一个HttpEntity
        HttpEntity httpEntity = multipartEntityBuilder.build();
        //将HttpEntity添加到psot请求中
        httpPost.setEntity(httpEntity);
        //声明response响应模型
        CloseableHttpResponse httpResponse = null;
        //声明返回的response中的实体
        HttpEntity responseEntity = null;
        try {
            httpResponse = httpClient.execute(httpPost);
            responseEntity = httpResponse.getEntity();
            logger.info("响应状态为:" + httpResponse.getStatusLine());
            //String entity = EntityUtils.toString(responseEntity,"UTF-8");
            //System.out.println(entity);
            //Map jsonToMap  = JSONObject.parseObject(entity);
            //System.out.println(jsonToMap.get("data").getClass());
            //System.out.println(file.getName());
            //JSONObject jsonObject = (JSONObject)jsonToMap.get("data");
            //System.out.println("feature:"+jsonObject.get("feature"));
            //System.out.println(jsonObject.get("feature").getClass());

        }catch (ClientProtocolException e){
            e.printStackTrace();
        }catch (IOException ee){
            ee.printStackTrace();
        }finally { //释放全部资源
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (httpResponse != null) {
                    httpResponse.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return EntityUtils.toString(responseEntity,"UTF-8");
    }
}


2. HTTPS–post/get请求 带文件post请求


需要重写认证

package com.cly.utils.Http.https;

import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**自定义认证*/
public class MyX509TrustManager implements X509TrustManager {
    //认证全部置空
    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType)
            throws CertificateException {
    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType)
            throws CertificateException {
    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }
}
package com.cly.utils.Http.https;

import com.alibaba.fastjson.JSON;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.*;
import java.net.URL;
import java.util.Map;

/**
 * @author : CLy
 * @ClassName : httpsQuery
 * @date : 2020/7/8 16:27
 **/
public class httpsQuery {
    /**HTTPS
     * requestUrl : 请求路径
     * requestMethod : GET/POST请求方式,大写
     * param :请求参数(可为空)
     * header:请求头部数据(可为空)
     * */
    public static String httpsRequest(String requestUrl,String requestMethod,Map<String,String> param,Map<String,String> header){
        StringBuffer buffer=null;
        try{
            //创建SSLContext
            SSLContext sslContext=SSLContext.getInstance("SSL");
            TrustManager[] tm={new MyX509TrustManager()};//用自定义认证
            //初始化
            sslContext.init(null, tm, new java.security.SecureRandom());;
            //获取SSLSocketFactory对象
            SSLSocketFactory ssf=sslContext.getSocketFactory();
            URL url=new URL(requestUrl);
            HttpsURLConnection conn=(HttpsURLConnection)url.openConnection();//打开连接
            conn.setDoOutput(true);//开启输出
            conn.setDoInput(true);//开启输入
            conn.setUseCaches(false);//开启缓存
            conn.setRequestMethod(requestMethod);//设置访问方式
            /*设置头部参数*/
            //设置请求头部信息
            for (Map.Entry<String, String> entry : header.entrySet()) {
                conn.setRequestProperty(entry.getKey(),entry.getValue());
                //conn.setRequestProperty("Content-Type", "application/json;charset=utf8");
                //conn.setRequestProperty("请求头部参数名", "请求头部参数值");
            }
            //设置当前实例使用的SSLSoctetFactory
            conn.setSSLSocketFactory(ssf);
            conn.connect();//连接
            //param请求参数转为json格式
            String outputStr =null;
            if (param.size()>0){
                JSON json = (JSON) JSON.toJSON(param);
                outputStr = json.toJSONString();
            }
            //往服务器端写入请求参数
            if(null!=outputStr){
                OutputStream outputStream=conn.getOutputStream();
                outputStream.write(outputStr.getBytes("utf-8"));
                outputStream.flush();//刷新
                outputStream.close();
            }
            //读取服务器端返回的内容
            InputStream inputStream=conn.getInputStream();
            InputStreamReader inputStreamReader=new InputStreamReader(inputStream,"utf-8");
            BufferedReader br=new BufferedReader(inputStreamReader);
            buffer=new StringBuffer();
            String line=null;
            while((line=br.readLine())!=null){
                buffer.append(line);
            }
            inputStream.close();
            inputStreamReader.close();
            br.close();
            conn.disconnect();//关闭连接
        }catch(Exception e){
            e.printStackTrace();
        }
        return buffer.toString();//返回响应数据
    }

    /**HTTPS 固定POST请求
     * requestUrl : 请求路径
     * File : 请求文件(可为空)
     * param :请求参数(可为空)
     * header:请求头部数据(可为空)
     * */
    public static String httpsPostWithFile(String requestUrl,File file, Map<String,String> param, Map<String,String> header){
        StringBuffer buffer=null;
        try{
            //创建SSLContext
            SSLContext sslContext=SSLContext.getInstance("SSL");
            TrustManager[] tm={new MyX509TrustManager()};//用自定义认证
            //初始化
            sslContext.init(null, tm, new java.security.SecureRandom());;
            //获取SSLSocketFactory对象
            SSLSocketFactory ssf=sslContext.getSocketFactory();
            URL url=new URL(requestUrl);
            HttpsURLConnection conn=(HttpsURLConnection)url.openConnection();//打开连接
            conn.setDoOutput(true);//开启输出
            conn.setDoInput(true);//开启输入
            conn.setUseCaches(false);//开启缓存
            conn.setRequestMethod("POST");//设置访问方式
            /*设置头部参数*/
            //设置请求头部信息
            for (Map.Entry<String, String> entry : header.entrySet()) {
                conn.setRequestProperty(entry.getKey(),entry.getValue());
                //conn.setRequestProperty("Content-Type", "application/json;charset=utf8");
                //conn.setRequestProperty("请求头部参数名", "请求头部参数值");
            }
            //设置当前实例使用的SSLSoctetFactory
            conn.setSSLSocketFactory(ssf);
            conn.connect();//连接
            //param请求参数转为json格式
            String outputStr =null;
            if (param.size()>0){
                JSON json = (JSON) JSON.toJSON(param);
                outputStr = json.toJSONString();
            }
            //往服务器端写入请求参数
            if(null!=outputStr){
                OutputStream outputStream=conn.getOutputStream();
                outputStream.write(outputStr.getBytes("utf-8"));//param请求参数写入
                //file写入
                FileInputStream fileInputStream =new FileInputStream(file);
                byte[] data = new byte[2048];
                int len = 0;
                while ((len = fileInputStream.read(data)) != -1) {
                    outputStream.write(data, 0, len);
                }
                outputStream.flush();//刷新
                fileInputStream.close();
                outputStream.close();
            }
            //读取服务器端返回的内容
            InputStream inputStream=conn.getInputStream();
            InputStreamReader inputStreamReader=new InputStreamReader(inputStream,"utf-8");
            BufferedReader br=new BufferedReader(inputStreamReader);
            buffer=new StringBuffer();
            String line=null;
            while((line=br.readLine())!=null){
                buffer.append(line);
            }
            inputStream.close();
            inputStreamReader.close();
            br.close();
            conn.disconnect();//关闭连接
        }catch(Exception e){
            e.printStackTrace();
        }
        return buffer.toString();//返回响应数据
    }
}

你可能感兴趣的:(java,http,https,post,get,java)