java使用httpclient发送put,delete,post,get(跳过https)

package com.coboriel.nbwatermeter.utils;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;


public class HttpRequestUtil {

    /**
     * post请求
     * @param url
     * @param param
     * @return
     * @throws IOException
     */
    public static String doPost(String url, String param)  {
        String result = null;
        HttpPost httpPost = new HttpPost(url);

        //配置ResquestConfig
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(15000).setConnectTimeout(15000).setConnectionRequestTimeout(15000).build();
        //配置StringEntity
        StringEntity stringEntity = new StringEntity(String.valueOf(param), "UTF-8");
        stringEntity.setContentType("application/x-www-form-urlencoded");

        //将Entity和Config设置到HttpPost
        httpPost.setEntity(stringEntity);
        httpPost.setConfig(requestConfig);

        CloseableHttpClient closeableHttpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setDefaultRequestConfig(requestConfig).build();
        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = closeableHttpClient.execute(httpPost);
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpEntity httpEntity = httpResponse.getEntity();
        if (httpEntity != null) {
            try {
                result = EntityUtils.toString(httpEntity, "UTF-8");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }


    /**
     * post请求
     * @param url
     * @param param
     * @param
     * @return header
     * @throws IOException
     */
    public static String doPostHeader(String url, String param,String accessToken) {
        String result = null;
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("app_key","a36f811fb78d49f688c8e35d66df4018");
        httpPost.setHeader("Authorization","Bearer " + accessToken);

        //配置ResquestConfig
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(15000).setConnectTimeout(15000).setConnectionRequestTimeout(15000).build();
        //配置StringEntity
        StringEntity stringEntity = new StringEntity(String.valueOf(param), "UTF-8");
        stringEntity.setContentType("application/json");

        //将Entity和Config设置到HttpPost
        httpPost.setEntity(stringEntity);
        httpPost.setConfig(requestConfig);

        CloseableHttpClient closeableHttpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setDefaultRequestConfig(requestConfig).build();
        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = closeableHttpClient.execute(httpPost);
            httpResponse.getStatusLine().getStatusCode();
            System.out.println("swss  " + httpResponse.getStatusLine().getStatusCode());
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpEntity httpEntity = httpResponse.getEntity();

        if (httpEntity != null) {
            try {
                result = EntityUtils.toString(httpEntity, HTTP.UTF_8);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * put请求
     * @param url
     * @param param
     * @param accessToken
     * @return
     * @throws IOException
     */
    public static String doPut(String url, String param,String accessToken) throws IOException {
        String result = null;
        HttpPut httpPut = new HttpPut(url);
        httpPut.setHeader("app_key","a36f811fb78d49f688c8e35d66df4018");
        httpPut.setHeader("Authorization","Bearer " + accessToken);

        //配置ResquestConfig
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(15000).setConnectTimeout(15000).setConnectionRequestTimeout(15000).build();
        //配置StringEntity
        StringEntity stringEntity = new StringEntity(String.valueOf(param), "UTF-8");
        stringEntity.setContentType("application/json");

        //将Entity和Config设置到HttpPost
        httpPut.setEntity(stringEntity);
        httpPut.setConfig(requestConfig);

        CloseableHttpClient closeableHttpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setDefaultRequestConfig(requestConfig).build();
        CloseableHttpResponse httpResponse = closeableHttpClient.execute(httpPut);
        HttpEntity httpEntity = httpResponse.getEntity();

        if (httpEntity != null) {
            result = EntityUtils.toString(httpEntity, HTTP.UTF_8);
        }
        return result;
    }

    /**
     *
     * @param url
     * @throws IOException
     */
    public static String doDelete(String url,String accessToken) throws IOException {
        String result = null;

        // 创建Delete请求
        HttpDelete httpDelete = new HttpDelete(url);
        httpDelete.setHeader("app_key","a36f811fb78d49f688c8e35d66df4018");
        httpDelete.setHeader("Authorization","Bearer " + accessToken);

        // 配置信息
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(5000).setRedirectsEnabled(true).build();
        // 将上面的配置信息 运用到这个Delete请求里
        httpDelete.setConfig(requestConfig);

        CloseableHttpClient closeableHttpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setDefaultRequestConfig(requestConfig).build();
        CloseableHttpResponse httpResponse = closeableHttpClient.execute(httpDelete);
        HttpEntity httpEntity = httpResponse.getEntity();

        if (httpEntity != null) {
            result = EntityUtils.toString(httpEntity, HTTP.UTF_8);
        }
        return result;
    }


    /**
     * get
     * @param url
     * @param accessToken
     * @return
     * @throws IOException
     */
    public static String doGet(String url,String accessToken) throws IOException {
        String result = null;
        // 创建Delete请求
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("app_key","a36f811fb78d49f688c8e35d66df4018");
        httpGet.setHeader("Authorization","Bearer " + accessToken);

        // 配置信息
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(5000).setRedirectsEnabled(true).build();
        // 将上面的配置信息 运用到这个Delete请求里
        httpGet.setConfig(requestConfig);

        CloseableHttpClient closeableHttpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setDefaultRequestConfig(requestConfig).build();
        CloseableHttpResponse httpResponse = closeableHttpClient.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();

        if (httpEntity != null) {
            result = EntityUtils.toString(httpEntity, HTTP.UTF_8);
        }
        return result;
    }


    //创建SSL安全连接
    private static SSLConnectionSocketFactory createSSLConnSocketFactory() {
        SSLConnectionSocketFactory sslsf = null;
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

                @Override
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();
            sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {

                @Override
                public boolean verify(String arg0, SSLSession arg1) {
                    return true;
                }
                @Override
                public void verify(String host, SSLSocket ssl) throws IOException {
                }
                @Override
                public void verify(String host, X509Certificate cert) throws SSLException {
                }
                @Override
                public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
                }
            });
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
        return sslsf;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值