使用java代码调用第三方http请求工具类

本文详细介绍了在SpringBoot框架下,使用Java代码调用第三方HTTP请求的工具类实现方法,包括GET、POST、PUT等请求方式,以及无认证和基本认证的处理过程。

使用java代码调用第三方http请求工具类

pom文件

<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
 </dependency>

使用的是springboot框架,此处不必写版本号

工具类

@Slf4j
public class HttpUtils {
    private static final String CHARSET = "UTF-8";

    private static final String USERNAME = "Admin";

    private static final String PASSWORD = "password";

    public static String sendPostNoAuth(String url, String body) {
        return sendPostNoAuth(url, body, CHARSET);
    }

    public static String sendPostByBasicAuth(String url, String body) {
        return sendPostByBasicAuth(url, USERNAME, PASSWORD, body, CHARSET);
    }

    public static String sendPostNoAuth(String url, Map<String, String> param) {
        return sendPostNoAuth(url, param, CHARSET);
    }

    public static String sendPutNoAuth(String url, String body) {
        return sendPutNoAuth(url, body, CHARSET);
    }

    public static String sendPutByBasicAuth(String url, String body) {
        return sendPutByBasicAuth(url, USERNAME, PASSWORD, body, CHARSET);
    }

    public static String sendGetByBasicAuth(String url) {
        return sendGetByBasicAuth(url, USERNAME, PASSWORD, CHARSET);
    }


    public static String sendPostNoAuth(String url, String body, String encoding) {
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new StringEntity(body, encoding));
            httpPost.setHeader("Content-type", "application/json");
            response = client.execute(httpPost); //执行
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                resultString = EntityUtils.toString(entity, encoding);
            }
            EntityUtils.consume(entity);
        } catch (Exception e) {
            log.error("地址[ " + url + " ]请求失败", e);
            throw new RuntimeException("post请求失败。。。");
        } finally {
            try {
                if (client != null)
                    client.close();
                if (response != null)
                    response.close();
            } catch (Exception e) {
                throw new RuntimeException("资源关闭异常。。。");
            }
        }
        return resultString;
    }

    public static String sendPostNoAuth(String url, Map<String, String> param, String encoding) {
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, encoding);
                httpPost.setEntity(entity);
            }
            httpPost.setHeader("Content-type", "application/json");
            response = client.execute(httpPost); //执行
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                resultString = EntityUtils.toString(entity, encoding);
            }
            EntityUtils.consume(entity);
        } catch (Exception e) {
            log.error("地址[ " + url + " ]请求失败", e);
            throw new RuntimeException("post请求失败。。。");
        } finally {
            try {
                if (client != null)
                    client.close();
                if (response != null)
                    response.close();

            } catch (Exception e) {
                throw new RuntimeException("资源关闭异常。。。");
            }
        }
        return resultString;
    }

    public static String sendPostByBasicAuth(String url, String username, String password, String body, String encoding) {
        //登录认证
        String basicAuthentication = username + ":" + password;
        String message = Base64.getEncoder().encodeToString(basicAuthentication.getBytes());//加密

        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new StringEntity(body, encoding));
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setHeader("Authorization", "Basic " + message);//请求头,用于登录认证(按照dhis的要求将用户名和密码加密传输)
            response = client.execute(httpPost); //执行
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                resultString = EntityUtils.toString(entity, encoding);
            }
            EntityUtils.consume(entity);
        } catch (Exception e) {
            log.error("地址[ " + url + " ]请求失败", e);
            throw new RuntimeException("post请求失败。。。");
        } finally {
            try {
                if (client != null)
                    client.close();
                if (response != null)
                    response.close();
            } catch (Exception e) {
                throw new RuntimeException("资源关闭异常。。。");
            }
        }
        return resultString;
    }

    public static String sendPutNoAuth(String url, String body, String encoding) {
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            HttpPut httpPut = new HttpPut(url);//创建http连接
            httpPut.setEntity(new StringEntity(body, encoding));
            httpPut.setHeader("Content-type", "application/json");
            response = client.execute(httpPut); //客户端执行。发送数据

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                resultString = EntityUtils.toString(entity, encoding);
            }
            EntityUtils.consume(entity);
        } catch (Exception e) {
            log.error("地址[ " + url + " ]请求失败", e);
            throw new RuntimeException("put请求失败。。。");
        } finally {
            try {
                if (client != null)
                    client.close();
                if (response != null)
                    response.close();

            } catch (Exception e) {
                throw new RuntimeException("资源关闭异常。。。");
            }
        }
        return resultString;

    }

    public static String sendPutByBasicAuth(String url, String username, String password, String body, String encoding) {
        //登录认证
        String basicAuthentication = username + ":" + password;
        String message = Base64.getEncoder().encodeToString(basicAuthentication.getBytes());//加密

        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            HttpPut httpPut = new HttpPut(url);//创建http连接
            httpPut.setEntity(new StringEntity(body, encoding));
            httpPut.setHeader("Content-type", "application/json");
            httpPut.setHeader("Authorization", "Basic " + message);//请求头,用于登录认证(按照dhis的要求将用户名和密码加密传输)
            response = client.execute(httpPut); //客户端执行。发送数据

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                resultString = EntityUtils.toString(entity, encoding);
            }
            EntityUtils.consume(entity);
        } catch (Exception e) {
            log.error("地址[ " + url + " ]请求失败", e);
            throw new RuntimeException("put请求失败。。。");
        } finally {
            try {
                if (client != null)
                    client.close();
                if (response != null)
                    response.close();

            } catch (Exception e) {
                throw new RuntimeException("资源关闭异常。。。");
            }
        }
        return resultString;

    }


    public static String sendGetNoAuth(String url, String encoding) {
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            HttpGet httpGet = new HttpGet(url);//创建http连接
            response = client.execute(httpGet); //客户端执行。发送数据
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                resultString = EntityUtils.toString(entity, encoding);
            }
            EntityUtils.consume(entity);
        } catch (Exception e) {
            log.error("地址[ " + url + " ]请求失败", e);
            throw new RuntimeException("get请求失败。。。");
        } finally {
            try {
                if (client != null)
                    client.close();
                if (response != null)
                    response.close();

            } catch (Exception e) {
                throw new RuntimeException("资源关闭异常。。。");
            }
        }
        return resultString;
    }


    public static String sendGetNoAuth(String url, Map<String, String> param, String encoding) {
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            HttpGet httpGet = new HttpGet(url);//创建http连接
            response = client.execute(httpGet); //客户端执行。发送数据
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                resultString = EntityUtils.toString(entity, encoding);
            }
            EntityUtils.consume(entity);
        } catch (Exception e) {
            log.error("地址[ " + url + " ]请求失败", e);
            throw new RuntimeException("get请求失败。。。");
        } finally {
            try {
                if (client != null)
                    client.close();
                if (response != null)
                    response.close();

            } catch (Exception e) {
                throw new RuntimeException("资源关闭异常。。。");
            }
        }
        return resultString;
    }

    public static String sendGetByBasicAuth(String url, String username, String password, String encoding) {
        //登录认证
        String basicAuthentication = username + ":" + password;
        String message = Base64.getEncoder().encodeToString(basicAuthentication.getBytes());//加密

        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            HttpGet httpGet = new HttpGet(url);//创建http连接
            httpGet.setHeader("Authorization", "Basic " + message);//请求头,用于登录认证(按照dhis的要求将用户名和密码加密传输)
            /* ************************************************************************* */
            httpGet.setHeader("Accept", "application/json");
            /* ************************************************************************* */
            response = client.execute(httpGet); //客户端执行。发送数据
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                resultString = EntityUtils.toString(entity, encoding);
            }
            EntityUtils.consume(entity);
        } catch (Exception e) {
            log.error("地址[ " + url + " ]请求失败", e);
            throw new RuntimeException("get请求失败。。。");
        } finally {
            try {
                if (client != null)
                    client.close();
                if (response != null)
                    response.close();

            } catch (Exception e) {
                throw new RuntimeException("资源关闭异常。。。");
            }
        }
        return resultString;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值