java两种不同的发送http请求的方式

第一种:apache的httpClient

public static String formPost(String url,Map<String,String> params, String charset) {
    if (StringUtils.isBlank(url)
            || StringUtils.isBlank(charset)
            || null == params) {
        return null;
    }
    CloseableHttpClient httpClient = HttpClients.createDefault();
    List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
    for (String key:params.keySet()) {
        if (StringUtils.isBlank(key)) {
            continue;
        }
        String value = params.get(key);
        if (StringUtils.isBlank(value)) {
            continue;
        }
        list.add(new BasicNameValuePair(key, value));
    }
    try {
        HttpPost post = new HttpPost(url);
        post.setEntity(new UrlEncodedFormEntity(list, charset));
        HttpResponse response = httpClient.execute(post);
        HttpEntity responseEntity = response.getEntity();
        if (null == responseEntity) {
            return null;
        }
        return EntityUtils.toString(responseEntity);
    }catch (Exception e) {
        LogUtils.error("http_post_form_error", e);
    }finally {
        try {
            httpClient.close();
        }catch (Exception e) {
            LogUtils.error("close_http_client_error", e);
        }
    }
    return null;
}


public static HttpClient getHttpsClient(String credentialPath, String credentialPassword) throws Exception{
    if (StringUtils.isBlank(credentialPassword)
            || StringUtils.isBlank(credentialPath)) {
        return null;
    }
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream inputStream = new FileInputStream(credentialPath);
    try {
        keyStore.load(inputStream, credentialPassword.toCharArray());
    } finally {
        inputStream.close();
    }
    SSLContext sslContext = SSLContexts
            .custom()
            .loadKeyMaterial(keyStore, credentialPassword.toCharArray())
            .build();
    SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(
            sslContext,
            new String[]{"TLSv1"},
            null,
            SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    CloseableHttpClient httpClient = HttpClients
            .custom()
            .setSSLSocketFactory(factory)
            .build();
    return httpClient;
}

public static String httpGet(String url,Map<String,String> map, int timeOut) {
    if (StringUtils.isBlank(url)
            || null == map) {
        return null;
    }
    String queryString = ParseUtils.getQueryString(map);
    if (StringUtils.isBlank(queryString)) {
        return null;
    }
    CloseableHttpClient httpClient = HttpClients.createDefault();
    timeOut = timeOut == 0 ? 60 : timeOut;
    try {
        url = url + "?" + queryString;
        HttpGet httpGet = new HttpGet(url);
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(timeOut * 1000)
                .setSocketTimeout(timeOut * 1000)
                .build();
        httpGet.setConfig(config);
        HttpResponse response =  httpClient.execute(httpGet);
        HttpEntity responseEntity = response.getEntity();
        if (null == responseEntity) {
            return null;
        }
        return EntityUtils.toString(responseEntity);
    }catch (Exception e) {
        LogUtils.error("http_get_error", e);
    }finally {
        try {
            httpClient.close();
        }catch (Exception e) {
            LogUtils.error("close_http_client_error", e);
        }
    }
    return null;
}
 

第二种:jdk自带的功能

public class HttpUtils {

    private static final int BUFFER_SIZE = 2048;

    public static Map<String,String> senPostRequest(String url, String bodyParams,String accessKey,String signKey) {
        URL connUrl = null;
        HttpURLConnection conn = null;
        String retn = null;
        OutputStream outStream = null;
        InputStream inStream = null;
        Map<String,String> resultMap = new HashMap<String, String>();
        Map<String, String> headParams = genHeadMessage(bodyParams,accessKey,signKey);
        try {
            // 打开URL连接
            connUrl = new URL(url);
            conn = (HttpURLConnection) connUrl.openConnection();

            // 设置HEAD信息
            if (headParams != null) {
                for (String key : headParams.keySet()) {
                    conn.setRequestProperty(key, headParams.get(key));
                }
            }

            if (connUrl.getProtocol().equals("https")) {
                ignoreSSLVerify((HttpsURLConnection) conn);
            }

            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            outStream = conn.getOutputStream();
            if(StringUtils.isNotBlank(bodyParams)){
                outStream.write(bodyParams.getBytes("UTF-8"));
            }
            outStream.flush();

            // 获取返回结果
            int code = conn.getResponseCode();
            if (code >= 200 && code < 300 && code != 0) {
                inStream = conn.getInputStream();
            } else {
                inStream = conn.getErrorStream();
            }
            byte[] bin = readInputStream(inStream);
            retn = new String(bin, "UTF-8");
            String sign = conn.getHeaderField("x-api-sign");
            resultMap.put("sign",sign);
            resultMap.put("params",retn);
        }catch (Exception e){
            LogUtils.error("xingyebank_hrtp_post_is_exception",e);
        }finally {
            if (inStream != null) {
                try {
                    inStream.close();
                    if (outStream != null) {
                        outStream.close();
                    }
                    if (conn != null) {
                        conn.disconnect();
                    }
                } catch (IOException e) {
                    LogUtils.error("xingyebank_hrtp_post_closeIO_is_exception",e);
                }
            }

        }
        return resultMap;
    }

    private static byte[] readInputStream(InputStream inStream) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] data = null;
        byte[] buffer = new byte[BUFFER_SIZE];
        int len = 0;
        try {
            while ((len = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            data = outStream.toByteArray();
        } finally {
            if (outStream != null) {
                outStream.close();
            }
        }
        return data;
    }

    public static void ignoreSSLVerify(HttpsURLConnection conn)
            throws NoSuchAlgorithmException, KeyManagementException {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }
        } };

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());

        conn.setSSLSocketFactory(sc.getSocketFactory());

        conn.setHostnameVerifier(new HostnameVerifier() {

            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
    }

    private static Map<String, String> genHeadMessage(String body,String accessKey,String signKey) {
        Map<String, String> head = new HashMap<String, String>();
        head.put("Accept", "application/json");
        head.put("Content-Type", "application/json;charset=utf-8");
        head.put("Content-Length", "256");
        head.put("x-api-accessKey", accessKey);
        head.put("x-api-signType", "MD5");
        head.put("x-api-sign", SignUtils.md5(body+signKey));
        LogUtils.temp("xingyebangk_do_signStr signStr="+SignUtils.md5(body+signKey));
        return head;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值