Java进行http请求工具类代码(支持https)

package com.guyezhai.modules.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;

public class HttpUtils {

    /**
     * POST请求远程http页面
     *
     * @param contentUrl
     * @param params
     * @return
     */
    public static String post(String contentUrl, Map<String, Object> params) {
        StringBuilder contentBuilder = new StringBuilder();
        HttpURLConnection connection = null;
        DataOutputStream out = null;
        BufferedReader reader = null;
        try {
            connection = (HttpURLConnection) new URL(contentUrl).openConnection();
            // 设置Socket超时
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(20000);
            // Post 请求不能使用缓存
            connection.setUseCaches(false);
            // URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);// 是否输入参数
            // 要注意的是connection.getOutputStream会隐含的进行connect
            connection.connect();

            out = new DataOutputStream(connection.getOutputStream());
            StringBuilder parambBuilder = new StringBuilder();
            if (params != null) {
                for (Entry<String, Object> e : params.entrySet()) {
                    parambBuilder.append(e.getKey()).append("=").append(URLEncoder.encode(String.valueOf(e.getValue()), "UTF-8")).append("&");
                }
                parambBuilder.deleteCharAt(parambBuilder.length() - 1);
            }
            // DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面
            out.writeBytes(parambBuilder.toString());
            out.flush();

            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));

            int buffer = 0;
            while ((buffer = reader.read()) != -1) {
                contentBuilder.append((char) buffer);
            }

        } catch (Exception e) {
            // 异常处理
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }

            if (connection != null) {
                connection.disconnect();
            }
        }
        return contentBuilder.toString();
    }

    /**
     * Get方法请求
     *
     * @param contentUrl
     * @return
     */
    public static String get(String contentUrl) {
        StringBuilder contentBuilder = new StringBuilder();
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        try {
            connection = (HttpURLConnection) new URL(contentUrl).openConnection();
            // 设置Socket超时
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(20000);
            connection.setRequestMethod("GET");
            connection.connect();

            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));

            int buffer = 0;
            while ((buffer = reader.read()) != -1) {
                contentBuilder.append((char) buffer);
            }
        } catch (Exception e) {
            // 异常处理
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
        return contentBuilder.toString();
    }

    /**
     * POST请求远程https页面
     *
     * @param contentUrl
     * @param params
     * @return
     */
    public static String postHttps(String contentUrl, Map<String, Object> params) {
        StringBuilder contentBuilder = new StringBuilder();
        HttpsURLConnection connection = null;
        DataOutputStream out = null;
        BufferedReader reader = null;
        try {
            HostnameVerifier hnv = new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            };

            X509TrustManager trustManager = new X509TrustManager() {
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

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

                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType) {
                }
            };

            X509TrustManager[] xtmArray = new X509TrustManager[] { trustManager };
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, xtmArray, new java.security.SecureRandom());

            if (sslContext != null) {
                HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
            }
            HttpsURLConnection.setDefaultHostnameVerifier(hnv);

            connection = (HttpsURLConnection) new URL(contentUrl).openConnection();
            // 设置Socket超时
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(20000);
            // Post 请求不能使用缓存
            connection.setUseCaches(false);
            // URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);// 是否输入参数
            connection.connect();

            out = new DataOutputStream(connection.getOutputStream());
            StringBuilder parambBuilder = new StringBuilder();
            if (params != null) {
                for (Entry<String, Object> e : params.entrySet()) {
                    parambBuilder.append(e.getKey()).append("=").append(URLEncoder.encode(String.valueOf(e.getValue()), "UTF-8")).append("&");
                }
                parambBuilder.deleteCharAt(parambBuilder.length() - 1);
            }
            // DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面
            out.writeBytes(parambBuilder.toString());
            out.flush();

            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));

            int buffer = 0;
            while ((buffer = reader.read()) != -1) {
                contentBuilder.append((char) buffer);
            }
        } catch (Exception e) {
            // 异常处理
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
        return contentBuilder.toString();
    }

}
时间: 2024-10-05 12:07:17

Java进行http请求工具类代码(支持https)的相关文章

java图片裁剪处理工具类代码

剪切前:  原文:java图片裁剪处理工具类代码 源代码下载地址:http://www.zuidaima.com/share/1550463351786496.htm 剪切后:  package com.zuidaima.zhangjun.image; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import

java多媒体文件编码要怎么写,处理工具类代码实例详情介绍

这篇文章主要介绍了java多媒体文件编码 处理工具类使用解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 引入 <dependency> <groupId>org.apache.storm</groupId> <artifactId>storm-core</artifactId> <version>1.1.0</version> </dependency>

java jdk原生的http请求工具类

package com.base; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.net.HttpURLConnection; import java.net.SocketTimeoutException; import java.net

java中常用的工具类

一.String工具类 package com.itjh.javaUtil; import java.util.ArrayList; import java.util.List; /** * * String工具类. <br> * * @author 宋立君 * @date 2014年06月24日 */ public class StringUtil { private static final int INDEX_NOT_FOUND = -1; private static final St

Java常用正则表达式验证工具类RegexUtils.java

原文:Java常用正则表达式验证工具类RegexUtils.java 源代码下载地址:http://www.zuidaima.com/share/1550463379442688.htm Java 表单注册常用正则表达式验证工具类,常用正则表达式大集合. 1. 电话号码 2. 邮编 3. QQ 4. E-mail 5. 手机号码 6. URL 7. 是否为数字 8. 是否为中文 9. 身份证 10. 域名 11. IP .... 常用验证应有尽有! 这的确是您从事 web 开发,服务器端表单验证

iOS_21团购_通过block对请求工具类的代理方法进行二次封装

最终效果图: [点评]提供的工具类DPAPI 在请求完毕后,使用的是代理机制,当一次请求成功或者失败时,会调用代理的相应方法 为了将点评提供的工具类DPAPI进行二次封装, 再次定义了一个block: typedef  void(^RequestDoneCallBackBlock)(id deals,NSError *err); 该block有两个参数, 分别是成功时,服务器返回的deals字典数组 另一个参数是:请求失败时,服务器返回的失败信息 两个参数分别对应代理的两个方法(即成功.失败时分

java中常用的工具类(二)

下面继续分享java中常用的一些工具类,希望给大家带来帮助! 1.FtpUtil Java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71

分享万能java字符串编码转换工具类

代码下载地址:http://www.zuidaima.com/share/1795356301560832.htm 原文:分享万能java字符串编码转换工具类 package com.zuidaima.util; import java.io.UnsupportedEncodingException; /** * 转换字符串的编码 */ public class ChangeCharset { /** 7位ASCII字符,也叫作ISO646-US.Unicode字符集的基本拉丁块 */ publ

我的Android进阶之旅------&gt;Android关于HttpsURLConnection一个忽略Https证书是否正确的Https请求工具类

下面是一个Android HttpsURLConnection忽略Https证书是否正确的Https请求工具类,不需要验证服务器端证书是否正确 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEn