调用第三方接口:Http请求工具类

news2024/9/29 5:32:49

在对接第三方接口时,需要进行数据交互,于是写了一个 Java 的 Http 请求工具类,该工具类可以调用 Get 请求或者 POST 请求。

根据自己业务需求灵活修改,这里写了两个工具类,自己选一个就可以

直接上代码:

添加依赖:

        <!--提供高效的、最新的、功能丰富的支持HTTP协议的客户端-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5</version>
        </dependency>

工具类1:

package com.file.license.utils;

import org.apache.http.HttpEntity;
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.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.net.*;
import java.util.Map;
import java.util.Set;

/**
 * @ClassName HttpUtils
 * @Description 请求工具
 * @Author msx
 * @Date 2021-08-26 17:40
 * @Version 1.0
 */
public class HttpUtils {
    
    /**
     * @Description get请求,参数k-v形式
     * @Author msx
     * @Date 2021-08-26 17:41
     * @param url-[请求地址] headMap-[请求头参数] paramMap-[请求参数]
     * @return String 返回结果
     */
    public static String doGet(String url, Map<String, String> headMap, Map<String, String> paramMap) {
        System.out.println(" = = 请求地址 = = > > > > > > " + url);
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = "";
        CloseableHttpResponse response = null;
        try {
            //创建uri
            URIBuilder builder = new URIBuilder(url);
            if (paramMap != null && !paramMap.isEmpty()) {
                Set<Map.Entry<String, String>> entrySet = paramMap.entrySet();
                for (Map.Entry<String, String> entry : entrySet) {
                    builder.addParameter(entry.getKey(), entry.getValue());
                }
            }
            URI uri = builder.build();

            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);

            //添加请求头
            if (headMap != null && !headMap.isEmpty()) {
                Set<Map.Entry<String, String>> entries = headMap.entrySet();
                System.out.println(" = = 请求头 = = > > > > > > ");
                for (Map.Entry<String, String> e : entries) {
                    System.out.println(e.getKey() + ":" + e.getValue());
                    httpGet.addHeader(e.getKey(), e.getValue());
                }
            }

            // 执行请求
            response = httpClient.execute(httpGet);
            // 判断返回状态是否为200
            /*if (response.getStatusLine().getStatusCode() == 200) {
                result = EntityUtils.toString(response.getEntity(), "UTF-8");
            }*/
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, "utf-8");
            System.out.println(" = = 请求返回 = = > > > > > > " + result);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeResource(response, httpClient);
        }
        return result;
    }

    /**
     * @Description post请求,参数k-v形式
     * @Author msx
     * @Date 2021-08-29 21:13
     * @param url-[请求地址] headMap-[请求头参数] paramMap-[请求参数]
     * @return String 返回结果
     */
    public static String doPost(String url, Map<String, String> headMap, Map<String, String> paramMap) {
        System.out.println(" = = 请求地址 = = > > > > > > " + url);
        System.out.println(" = = 请求参数 = = > > > > > > " + paramMap);
        //创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = "";
        try{
            //创建uri
            URIBuilder builder = new URIBuilder(url);
            if (paramMap != null && !paramMap.isEmpty()) {
                Set<Map.Entry<String, String>> entrySet = paramMap.entrySet();
                for (Map.Entry<String, String> entry : entrySet) {
                    builder.addParameter(entry.getKey(), entry.getValue());
                }
            }
            URI uri = builder.build();
            //创建http请求
            HttpPost httpPost = new HttpPost(uri);
            //添加请求头
            if (headMap != null && !headMap.isEmpty()) {
                System.out.println(" = = 请求头 = = > > > > > > ");
                Set<Map.Entry<String, String>> entries = headMap.entrySet();
                for (Map.Entry<String, String> entry : entries) {
                    System.out.println(entry.getKey() + ":" + entry.getValue());
                    httpPost.addHeader(entry.getKey(), entry.getValue());
                }
            }
            // 执行请求
            response = httpClient.execute(httpPost);
            result = EntityUtils.toString(response.getEntity(), "utf-8");
            System.out.println(" = = 请求返回 = = > > > > > > " + result);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭资源
            closeResource(response, httpClient);
        }
        return result;
    }

    /**
     * @Description post请求,请求体为JSON格式
     * @Author msx
     * @Date 2021-08-27 16:31
     * @param url-[请求地址] headMap-[请求头参数] paramMap-[请求参数]
     * @return String 返回结果
     */
    public static String doPost(String url, Map<String, String> header, String jsonParams){
        System.out.println(" = = 请求地址 = = > > > > > > " + url);
        System.out.println(" = = 请求参数 = = > > > > > > " + jsonParams);
        //创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = "";
        try{
            //创建http请求
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/json");
            //创建请求内容
            StringEntity entity = new StringEntity(jsonParams, "utf-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            // 设置请求头
            if (null != header && !header.isEmpty()) {
                System.out.println(" = = 请求头 = = > > > > > > ");
                Set<Map.Entry<String, String>> entries = header.entrySet();
                for (Map.Entry<String, String> e : entries) {
                    System.out.println(e.getKey() + ":" + e.getValue());
                    httpPost.setHeader(e.getKey(), e.getValue());
                }
            }
            response = httpClient.execute(httpPost);
            result = EntityUtils.toString(response.getEntity(), "utf-8");
            System.out.println(" = = 请求返回 = = > > > > > > " + result);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭资源
            closeResource(response, httpClient);
        }
        return result;
    }

    /**
     * @Description 关闭资源
     * @Author msx
     * @Date 2021/9/8 10:44
     */
    private static void closeResource(Closeable ... resources) {
        System.out.println("> > > > > > > > > > 关闭流资源 > > > > > > > > > >");
        try {
            for (Closeable resource : resources) {
                if (resource != null) {
                    resource.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

测试:

package com.ynkbny.web.controller;

import com.ynkbny.util.HttpUtils;
import com.ynkbny.util.Res;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * 老狗Api接口-控制层
 *
 * @author : juzipi123
 * @date : 2023-7-17
 */
@Slf4j
@Api(tags = "Api接口")
@RestController
@RequestMapping("/api")
public class LaoGouApiController {

    /**
     * 登陆
     *
     * @author : juzipi
     * @param username 用户名
     * @param password 密码
     * @return 结果
     */
    @ApiOperation("登陆")
    @RequestMapping("/login")
    public Res<String> login(String username ,String password) throws Exception {
        log.info("请求参数:{},{}",username,password);
        String url = "https://api.bknykf.com/api/user/login"+"?username="+username+"&password="+password;
//        return Res.ok(HttpUtils.doGet(url, null,null));
        return Res.ok(HttpUtils.doPost(url, null,""));
    }
}

测试结果:

工具类2:

package com.ynkbny.util;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * HTTP请求工具
 *
 * @author Smaple
 */
public class HttpClientUtils {

    private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    private final static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);

    /**
     * 最大线程池
     */
    public static final int THREAD_POOL_SIZE = 5;

    public interface HttpClientDownLoadProgress {
        public void onProgress(int progress);
    }

    private static HttpClientUtils httpClientDownload = new HttpClientUtils();

    private ExecutorService downloadExcutorService;

    private HttpClientUtils() {
        downloadExcutorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
    }

    public static HttpClientUtils getInstance() {
        return httpClientDownload;
    }

    /**
     * 下载文件
     *
     * @param url
     * @param filePath
     */
    public void download(final String url, final String filePath) {
        downloadExcutorService.execute(new Runnable() {
            @Override
            public void run() {
                httpDownloadFile(url, filePath, null, null);
            }
        });
    }

    /**
     * 下载文件
     *
     * @param url
     * @param filePath
     * @param progress 进度回调
     */
    public void download(final String url, final String filePath,
                         final HttpClientDownLoadProgress progress) {
        downloadExcutorService.execute(new Runnable() {
            @Override
            public void run() {
                httpDownloadFile(url, filePath, progress, null);
            }
        });
    }

    /**
     * 下载文件
     *
     * @param url
     * @param filePath
     */
    private void httpDownloadFile(String url, String filePath,
                                  HttpClientDownLoadProgress progress, Map<String, String> headMap) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httpGet = new HttpGet(url);
            setGetHead(httpGet, headMap);
            CloseableHttpResponse response1 = httpclient.execute(httpGet);
            try {
                HttpEntity httpEntity = response1.getEntity();
                long contentLength = httpEntity.getContentLength();
                InputStream is = httpEntity.getContent();
                // 根据InputStream 下载文件
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                byte[] buffer = new byte[4096];
                int r = 0;
                long totalRead = 0;
                while ((r = is.read(buffer)) > 0) {
                    output.write(buffer, 0, r);
                    totalRead += r;
                    if (progress != null) {// 回调进度
                        progress.onProgress((int) (totalRead * 100 / contentLength));
                    }
                }
                FileOutputStream fos = new FileOutputStream(filePath);
                output.writeTo(fos);
                output.flush();
                output.close();
                fos.close();
                EntityUtils.consume(httpEntity);
            } finally {
                response1.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * get请求
     *
     * @param url
     * @return
     */
    public String httpGet(String url) {
        return httpGet(url, null);
    }

    /**
     * http get请求
     *
     * @param url
     * @return
     */
    public String httpGet(String url, Map<String, String> headMap) {
        String responseContent = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httpGet = new HttpGet(url);
            CloseableHttpResponse response1 = httpclient.execute(httpGet);
            setGetHead(httpGet, headMap);
            try {
                HttpEntity entity = response1.getEntity();
                responseContent = getRespString(entity);
                EntityUtils.consume(entity);
            } finally {
                response1.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContent;
    }

    public String httpPost(String url, Map<String, String> paramsMap) {
        return httpPost(url, paramsMap, null);
    }

    /**
     * http的post请求
     *
     * @param url
     * @param paramsMap
     * @return
     */
    public String httpPost(String url, Map<String, String> paramsMap,
                           Map<String, String> headMap) {
        String responseContent = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost(url);
            setPostHead(httpPost, headMap);
            setPostParams(httpPost, paramsMap);
            CloseableHttpResponse response = httpclient.execute(httpPost);
            try {
                HttpEntity entity = response.getEntity();
                responseContent = getRespString(entity);
                EntityUtils.consume(entity);
            } finally {
                response.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContent;
    }

    /**
     * 设置POST的参数
     *
     * @param httpPost
     * @param paramsMap
     * @throws Exception
     */
    private void setPostParams(HttpPost httpPost, Map<String, String> paramsMap)
            throws Exception {
        if (paramsMap != null && paramsMap.size() > 0) {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            Set<String> keySet = paramsMap.keySet();
            for (String key : keySet) {
                nvps.add(new BasicNameValuePair(key, paramsMap.get(key)));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, DEFAULT_CHARSET));
        }
    }

    /**
     * 设置http的HEAD
     *
     * @param httpPost
     * @param headMap
     */
    private void setPostHead(HttpPost httpPost, Map<String, String> headMap) {
        if (headMap != null && headMap.size() > 0) {
            Set<String> keySet = headMap.keySet();
            for (String key : keySet) {
                httpPost.addHeader(key, headMap.get(key));
            }
        }
    }


    /**
     * 设置http的HEAD
     *
     * @param httpGet
     * @param headMap
     */
    private void setGetHead(HttpGet httpGet, Map<String, String> headMap) {
        if (headMap != null && headMap.size() > 0) {
            Set<String> keySet = headMap.keySet();
            for (String key : keySet) {
                httpGet.addHeader(key, headMap.get(key));
            }
        }
    }

    /**
     * 上传文件
     *
     * @param serverUrl       服务器地址
     * @param localFilePath   本地文件路径
     * @param serverFieldName
     * @param params
     * @return
     * @throws Exception
     */
    public String uploadFileImpl(String serverUrl, String localFilePath,
                                 String serverFieldName, Map<String, String> params)
            throws Exception {
        String respStr = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httppost = new HttpPost(serverUrl);
            FileBody binFileBody = new FileBody(new File(localFilePath));

            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            // add the file params
            multipartEntityBuilder.addPart(serverFieldName, binFileBody);
            // 设置上传的其他参数
            setUploadParams(multipartEntityBuilder, params);

            HttpEntity reqEntity = multipartEntityBuilder.build();
            httppost.setEntity(reqEntity);

            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity resEntity = response.getEntity();
                respStr = getRespString(resEntity);
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
        return respStr;
    }


    public String httpsPost(String url, Map<String, String> heads, Map<String, String> params) throws Exception {
        String body = "";
        SSLContext sslcontext = createIgnoreVerifySSL();
        //设置协议http和https对应的处理socket链接工厂的对象
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", new SSLConnectionSocketFactory(sslcontext))
                .build();
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        HttpClients.custom().setConnectionManager(connManager);

        CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();

        try {
            //创建post方式请求对象
            HttpPost httpPost = new HttpPost(url);

            if (heads != null) {
                for (Map.Entry<String, String> head : heads.entrySet()) {
                    httpPost.setHeader(head.getKey(), head.getValue());
                }
            }
            setPostParams(httpPost, params);
            //执行请求操作,并拿到结果(同步阻塞)
            CloseableHttpResponse response = client.execute(httpPost);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                body = EntityUtils.toString(entity, "UTF-8");
            }
            EntityUtils.consume(entity);
            //释放链接
            response.close();
            return body;
        } finally {
            client.close();
        }
    }

    /**
     * 绕过验证
     *
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    private SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sc = SSLContext.getInstance("SSLv3");

        X509TrustManager trustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sc.init(null, new TrustManager[]{trustManager}, null);
        return sc;
    }


    /**
     * 设置上传文件时所附带的其他参数
     *
     * @param multipartEntityBuilder
     * @param params
     */
    private void setUploadParams(MultipartEntityBuilder multipartEntityBuilder,
                                 Map<String, String> params) {
        if (params != null && params.size() > 0) {
            Set<String> keys = params.keySet();
            for (String key : keys) {
                multipartEntityBuilder
                        .addPart(key, new StringBody(params.get(key),
                                ContentType.TEXT_PLAIN));
            }
        }
    }

    /**
     * 将返回结果转化为String
     *
     * @param entity
     * @return
     * @throws Exception
     */
    private String getRespString(HttpEntity entity) throws Exception {
        if (entity == null) {
            return null;
        }
        InputStream is = entity.getContent();
        StringBuffer strBuf = new StringBuffer();
        byte[] buffer = new byte[4096];
        int r = 0;
        while ((r = is.read(buffer)) > 0) {
            strBuf.append(new String(buffer, 0, r, "UTF-8"));
        }
        return strBuf.toString();
    }

    public static String postTimeout(String url, String requestBody, int millisecondTimeout, TimeOutErrorHandler errorHandler) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(millisecondTimeout).setConnectionRequestTimeout(millisecondTimeout)
                .setSocketTimeout(millisecondTimeout).build();
        httpPost.setConfig(requestConfig);
        CloseableHttpResponse response = null;
        StringEntity reqEntity = null;
        HttpEntity respEntity = null;
        try {
            reqEntity = new StringEntity(requestBody, DEFAULT_CHARSET);
            httpPost.setEntity(reqEntity);
            response = httpclient.execute(httpPost);
            respEntity = response.getEntity();
            int stateCode = response.getStatusLine().getStatusCode();
            if (200 != stateCode) {
                if (logger.isErrorEnabled()) {
                    logger.error("请求地址:{}, 响应码为:{}, 响应失败!", url, stateCode);
                }
                return null;
            }
            return EntityUtils.toString(response.getEntity(), DEFAULT_CHARSET);
        } catch (SocketTimeoutException e) {
            if (logger.isErrorEnabled()) {
                logger.error("请求地址:{}, 请求超时. 超时设置时间为:{}", url, millisecondTimeout);
            }
            if (errorHandler != null) errorHandler.handler(e);
            return null;
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error("请求地址:{}, 请求出错, 错误原因是:{}", url, e.getMessage());
            }
            return null;
        } finally {
            try {
                EntityUtils.consume(respEntity);
                EntityUtils.consume(reqEntity);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpclient != null) {
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public static String postProxyTimeout(String proxyIp, int proxyPort, String url, String requestBody, int millisecondTimeout, TimeOutErrorHandler errorHandler) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //设置代理IP、端口
        HttpHost proxy = new HttpHost(proxyIp, proxyPort, "http");
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom()
                .setProxy(proxy)
                .setConnectTimeout(millisecondTimeout).setConnectionRequestTimeout(millisecondTimeout)
                .setSocketTimeout(millisecondTimeout).build();
        httpPost.setConfig(requestConfig);
        CloseableHttpResponse response = null;
        StringEntity reqEntity = null;
        HttpEntity respEntity = null;
        try {
            reqEntity = new StringEntity(requestBody, DEFAULT_CHARSET);
            httpPost.setEntity(reqEntity);
            response = httpclient.execute(httpPost);
            respEntity = response.getEntity();
            int stateCode = response.getStatusLine().getStatusCode();
            if (200 != stateCode) {
                if (logger.isErrorEnabled()) {
                    logger.error("请求地址:{}, 响应码为:{}, 响应失败!", url, stateCode);
                }
                return null;
            }
            return EntityUtils.toString(response.getEntity(), DEFAULT_CHARSET);
        } catch (SocketTimeoutException e) {
            if (logger.isErrorEnabled()) {
                logger.error("请求地址:{}, 请求超时. 超时设置时间为:{}", url, millisecondTimeout);
            }
            if (errorHandler != null) errorHandler.handler(e);
            return null;
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error("请求地址:{}, 请求出错, 错误原因是:{}", url, e.getMessage());
            }
            return null;
        } finally {
            try {
                EntityUtils.consume(respEntity);
                EntityUtils.consume(reqEntity);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpclient != null) {
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public interface TimeOutErrorHandler {
        void handler(SocketTimeoutException e);
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();

            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!" + e);
            return null;
            //e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 发送post请求 携带json数据的
     * @param url
     * @param jsonStr
     */
    public static String sendPostMethod(String url, String jsonStr, String authorization) {

        String result = "";

        //1.创建httpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();

        //2.创建post请求方式实例
        HttpPost httpPost = new HttpPost(url);

        //2.1设置请求头 发送的是json数据格式
        httpPost.setHeader("Content-type", "application/json;charset=utf-8");
        httpPost.setHeader("Connection", "Close");

        if (ObjectUtils.isNotEmpty(authorization)) {
            httpPost.setHeader("Authorization", authorization);
        }

        //3.设置参数---设置消息实体 也就是携带的数据
        StringEntity entity = new StringEntity(jsonStr.toString(), Charset.forName("UTF-8"));
        //设置编码格式
        entity.setContentEncoding("UTF-8");
        // 发送Json格式的数据请求
        entity.setContentType("application/json");
        //把请求消息实体塞进去
        httpPost.setEntity(entity);

        //4.执行http的post请求
        CloseableHttpResponse httpResponse = null;
        InputStream inputStream = null;
        try {
            httpResponse = httpClient.execute(httpPost);

            // 5.对返回的数据进行处理
            // 5.1判断是否成功
            System.out.println(httpResponse.getStatusLine().getStatusCode());

            // 5.2对数据进行处理
            HttpEntity httpEntity = httpResponse.getEntity();

            //获取content实体内容
            inputStream = httpEntity.getContent();

            //封装成字符流来输出
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                result += line;
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            //6.关闭inputStream和httpResponse
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return result;
    }

    /**
     * 设置代理
     *
     * @param httpGet
     * @param proxyIp
     * @param proxyPort
     * @return
     */
    public CloseableHttpClient setProxy(HttpGet httpGet, String proxyIp, int proxyPort) {
        // 创建httpClient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //设置代理IP、端口
        HttpHost proxy = new HttpHost(proxyIp, proxyPort, "http");
        //也可以设置超时时间   RequestConfig requestConfig = RequestConfig.custom().setProxy(proxy).setConnectTimeout(3000).setSocketTimeout(3000).setConnectionRequestTimeout(3000).build();
        RequestConfig requestConfig = RequestConfig.custom().setProxy(proxy).build();
        httpGet.setConfig(requestConfig);
        return httpClient;
    }


    /**
     * 设置代理
     *
     * @param httpPost
     * @param proxyIp
     * @param proxyPort
     * @return
     */
    public static CloseableHttpClient setPostProxy(HttpPost httpPost, String proxyIp, int proxyPort) {
        // 创建httpClient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //设置代理IP、端口
        HttpHost proxy = new HttpHost(proxyIp, proxyPort, "http");
        //也可以设置超时时间   RequestConfig requestConfig = RequestConfig.custom().setProxy(proxy).setConnectTimeout(3000).setSocketTimeout(3000).setConnectionRequestTimeout(3000).build();
        RequestConfig requestConfig = RequestConfig.custom().setProxy(proxy).build();
        httpPost.setConfig(requestConfig);
        return httpClient;
    }


}

测试:

package com.ynkbny.web.controller;

import com.ynkbny.util.HttpClientUtils;
import com.ynkbny.util.Res;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Api接口-控制层
 *
 * @author : juzipi
 */
@Slf4j
@Api(tags = "Api接口")
@RestController
@RequestMapping("/api")
public class LaoGouApiController {

    /**
     * 登陆
     *
     * @author : juzipi
     * @param username 用户名
     * @param password 密码
     * @return 结果
     */
    @ApiOperation("登陆")
    @RequestMapping("/login")
    public Res<String> login(String username ,String password) throws Exception {
        log.info("请求参数:{},{}",username,password);
        String url = "https://api.bknykf.com/api/user/login"+"?username="+username+"&password="+password;
//        return Res.ok(sendPostMethod(url,""));
        return Res.ok(sendReq(url,""));
    }

    private static String sendReq(String reqUrl, String param) throws Exception {
        log.info("=====请求地址:" + reqUrl);
        log.info("=====请求数据:" + param);
        String result = HttpClientUtils.sendPost(reqUrl, param);
        log.info("=====响应数据:" + result);
        return result;
    }

    private static String sendPostMethod(String reqUrl, String param) throws Exception {
        log.info("=====请求地址:" + reqUrl);
        log.info("=====请求数据:" + param);
        String result = HttpClientUtils.sendPostMethod(reqUrl, param,null);
        log.info("=====响应数据:" + result);
        return result;
    }

}

测试结果:

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1550678.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Python模糊字符串匹配工具库之fuzzywuzzy使用详解

概要 Python的fuzzywuzzy库是一个强大的模糊字符串匹配工具,基于Levenshtein距离算法,可用于处理文本相似度匹配任务。本文将深入探讨fuzzywuzzy库的各种功能和用法,结合详细的描述和丰富的示例代码,带领大家全面了解这个工具的使用方法和实际应用场景。 安装 在开始使用…

【技巧】PyTorch限制GPU显存的可使用上限

转载请注明出处&#xff1a;小锋学长生活大爆炸[xfxuezhang.cn] 从 PyTorch 1.4 版本开始&#xff0c;引入了一个新的功能 torch.cuda.set_per_process_memory_fraction(fraction, device)&#xff0c;这个功能允许用户为特定的 GPU 设备设置进程可使用的显存上限比例。 测试代…

第115讲:Mycat核心配置文件各项参数的作用以及概念

文章目录 1.Mycat配置文件相关概念2.Schema配置文件3.Rule配置文件4.Server配置文件 1.Mycat配置文件相关概念 在Mycat中核心的配置文件有schema.xml和rule.xml以及server.xml三个&#xff0c;其中schema.xml是用来配置数据库、表、读写分离、分片节点、分片规则等信息&#x…

uniapp对接萤石云 实现监控播放、云台控制、截图、录像、历史映像等功能

萤石云开发平台地址&#xff1a;文档概述 萤石开放平台API文档 (ys7.com) 萤石云监控播放 首先引入萤石云js js地址&#xff1a;GitHub - Ezviz-OpenBiz/EZUIKit-JavaScript-npm: 轻应用npm版本&#xff0c;降低接入难度&#xff0c;适配自定义UI&#xff0c;适配主流框架 vi…

DC电源模块的设计与制造流程

BOSHIDA DC电源模块的设计与制造流程 DC电源模块是一种用于将交流电转换为直流电的设备。它广泛应用于各种电子设备中&#xff0c;如电子产品、工业仪器、电视等。下面是DC电源模块的设计与制造流程的简要描述&#xff1a; 1. 需求分析&#xff1a;在设计DC电源模块之前&#…

目标检测——服装数据集

一、重要性及意义 首先&#xff0c;服装检测是确保产品质量和安全性的关键环节。通过对服装的材质、工艺、安全性等方面的检测&#xff0c;可以及时发现并纠正可能存在的缺陷和问题&#xff0c;从而确保产品符合消费者的期望和要求。这有助于维护品牌形象&#xff0c;提高消费…

【Java程序设计】【C00360】基于Springboot的考研互助交流平台(有论文)

基于Springboot的考研互助交流平台&#xff08;有论文&#xff09; 项目简介项目获取开发环境项目技术运行截图 项目简介 项目获取 &#x1f345;文末点击卡片获取源码&#x1f345; 开发环境 运行环境&#xff1a;推荐jdk1.8&#xff1b; 开发工具&#xff1a;eclipse以及i…

day70 Mybatis使用mapper重构xml文件重新修改商品管理系统

day67 基于mysql数据库jdbcDruidjar包连接的商品管理用户购物系统-CSDN博客 1多表操作 2动态SQL 项目中使用的为商品管理系统的表 一 查询商品信息 编号&#xff0c;名称&#xff0c;单价&#xff0c;库存&#xff0c;类别 1表&#xff1a;商品表&#xff0c;类别表 n对1…

el-table中复选框、展开列、索引

<!-- 复选框&#xff0c;搭配selection-change"handleSelectChange"使用&#xff0c;每次点击复选框就会调用方法handleSelectChange(selection) {}&#xff0c;在该方法中只要调用该方法获取到的selection就是所有已勾选的记录集合 --> <el-table-column t…

【正点原子FreeRTOS学习笔记】————(14)事件标志组

这里写目录标题 一、事件标志组简介&#xff08;了解&#xff09;二、事件标志组相关API函数介绍&#xff08;熟悉&#xff09;三、事件标志组实验&#xff08;掌握&#xff09; 一、事件标志组简介&#xff08;了解&#xff09; 事件标志位&#xff1a;用一个位&#xff0c;来…

网站可扩展架构设计

从公众号转载&#xff0c;关注微信公众号掌握更多技术动态 --------------------------------------------------------------- 一、可扩展性架构简介 1.可扩展性是什么 可扩展性指系统为了应对将来需求变化而提供的一种扩展能力&#xff0c;当有新的需求出现时&#xff0c;系…

剑指Offer题目笔记19(二分查找)

面试题68&#xff1a; 问题&#xff1a; ​ 输入一个排序的整形数组nums和一个目标值t&#xff0c;如果数组nums中包含t&#xff0c;则返回在数组中的下标&#xff0c;否则返回按照顺序插入到数组的下标。 解决方案&#xff1a; ​ 使用二分查找。每次二分查找都选取位于数组…

CIM搭建实现发送消息的效果

目录 背景过程1、下载代码2、进行配置3、直接启动项目4、打开管理界面5、启动web客户端实例项目6、发送消息 项目使用总结 背景 公司项目有许多需要发送即时消息的场景&#xff0c;之前一直采用的是传统的websocket连接&#xff0c;它会存在掉线严重&#xff0c;不可重连&…

PCB经常连锡?或许你可以看看这三个焊盘

在印刷电路板&#xff08;PCB&#xff09;制造中&#xff0c;很容易遇见连锡问题&#xff0c;即相邻焊盘之间出现意外的锡桥连接&#xff0c;这主要是焊盘的设置不当&#xff0c;若是不及时处理&#xff0c;很可能导致电路短路&#xff0c;影响其正常功能。那么如何选择焊盘&am…

4.Python数据分析—数据分析入门知识图谱索引(知识体系下篇)

4.Python数据分析—数据分析入门知识图谱&索引-知识体系下篇 一个人简介二机器学习基础2.1 监督学习与无监督学习2.1.1 监督学习&#xff1a;2.1.2 无监督学习&#xff1a; 2.2 特征工程2.3 常用机器学习算法概述2.3.1 监督学习算法&#xff1a;2.3.2 无监督学习算法&#…

Redis 教程系列之Redis 集群配置(十三)

1.Redis集群方案比较 主从模式 在软件的架构中,主从模式(Master-Slave)是使用较多的一种架构。主(Master)和从(Slave)分别部署在不同的服务器上,当主节点服务器写入数据时,同时也会将数据同步至从节点服务器,通常情况下,主节点负责写入数据,而从节点负责读取数据。…

网络原理(6)——IP协议

目录 一、网段划分 现在的网络划分&#xff1a; 1、一般情况下的家庭网络环境 2、IP地址 3、子网掩码 4、网关 以前的网络划分&#xff1a; 二、特殊IP 1、环回 IP 2、主机号为全 0 的IP 3、广播地址IP 三、路由选择&#xff08;路线规划&#xff09; 一、网段划分…

零信任的应用场景和部署模式

零信任是新一代网络安全理念&#xff0c;并非指某种单一的安全技术或产品&#xff0c;其目标是为了降低资源访问过程中的安全风险&#xff0c;防止在未经授权情况下的资源访问&#xff0c;其关键是打破信任和网络位置的默认绑定关系。 一、零信任安全模型的核心理念可以概括为…

教育数字化调研团走进锐捷,共议职业教育数字化转型新思路

为贯彻落实国家教育数字化战略行动部署和2024年全国教育工作会议精神,加快推进职业教育数字化转型与发展,梳理职业教育数字化转型的现状、问题及发展趋势,并总结展示职业教育数字化转型的好经验、好做法,培育职业教育数字化创新成果,推动数字技术与职业教育深度融合、提高数字化…

fs.1.10 ON CENTOS7 docker镜像制作

概述 freeswitch是一款简单好用的VOIP开源软交换平台。 centos7 docker上编译安装fs1.10版本的流程记录。 环境 docker engine&#xff1a;Version 24.0.6 centos docker&#xff1a;7 freeswitch&#xff1a;v1.10.7 手动模式 centos准备 docker hub拉取centos镜像。…