工具类总结---(六)---之http及https请求

下面使用的是HttpURLConnection进行的网络链接,并对https进行了忽略证书。

在这个utils里面,也使用到前面几个utils,比如下载文件的方法,就使用到了Fileutils

package cgjr.com.cgjr.utils;

import android.text.TextUtils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

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

import cgjr.com.cgjr.constants.Constants;

/**
 * Created by Administrator on 2016/4/13.
 */
public class HttpUtils {

    /**
     * 通过http post 提交数据
     *
     * @param url      访问路径
     * @param content  内容
     * @param encoding 返回内容字符编码
     * @return
     */
    public static String HttpPost(String url, String content, String encoding) {
        DebugUtils.i("HttpUtils", "content: " + content);
        HttpURLConnection conn = null;
        String str = "";
        try {
            conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setDoInput(true);// 打开输入流,以便从服务器获取数据
            conn.setDoOutput(true);// 打开输出流,以便向服务器提交数据
            conn.setConnectTimeout(0); // 设置连接超时时间
            conn.setReadTimeout(30000); //设置返回超时时间,下面要对超时进行处理
            conn.setRequestMethod("POST");
            conn.setUseCaches(false);// 使用Post方式不能使用缓存
            conn.setInstanceFollowRedirects(true);
            //conn.setRequestProperty("Cookie", SessionId);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            conn.connect();
            DataOutputStream out = new DataOutputStream(conn.getOutputStream());
            out.writeBytes(content);
            out.flush();
            out.close(); // flush and close
            int response = conn.getResponseCode(); // 获得服务器的响应码
            if (response == HttpURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), encoding));
                StringBuffer sb = new StringBuffer();
                String line;
                while ((line = br.readLine()) != null) {
                    line = new String(line.getBytes(), "UTF-8");
                    sb.append(line);
                }
                str = sb.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            //里面会抛连接和返回超时java.net.SocketTimeoutException,还有IO异常
            return "faild";
        } finally {
            conn.disconnect();
            conn = null;
        }
        return str;
    }

    /**
     * GET请求方式
     *
     * @param url
     * @return
     */
    public static String HttpGet(String url, String encoding) {
        LogUtils.i("HttpUtils", "encoding: " + encoding);
        HttpURLConnection conn = null;
        String str = "";
        try {
            conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setDoInput(true);// 打开输入流,以便从服务器获取数据
            conn.setDoOutput(true);// 打开输出流,以便向服务器提交数据
            conn.setConnectTimeout(30000); // 设置连接超时时间
            conn.setReadTimeout(30000); //设置返回超时时间,下面要对超时进行处理
            conn.setRequestMethod("GET");
            conn.connect();
            int response = conn.getResponseCode(); // 获得服务器的响应码
            if (response == HttpURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), encoding));
                StringBuffer sb = new StringBuffer();
                String line;
                while ((line = br.readLine()) != null) {
                    line = new String(line.getBytes(), "UTF-8");
                    sb.append(line);
                }
                str = sb.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            //里面会抛连接和返回超时java.net.SocketTimeoutException,还有IO异常
            return "faild";
        } finally {
            if (conn != null)
                conn.disconnect();
        }
        return str;
    }

    /**
     * 通过https post 提交数据
     *
     * @param url      访问路径
     * @param content  内容
     * @param encoding 返回内容字符编码
     * @return
     */
    public static String HttpsPost(String url, String content, String encoding) {
        LogUtils.i("HttpUtils", "content: " + content);
        SSLContext sc = null;
        try {
            sc = SSLContext.getInstance("TLS");
            MyTrustManager mtm = new MyTrustManager();
            sc.init(null, new TrustManager[]{mtm}, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "faild";
        } catch (KeyManagementException e) {
            e.printStackTrace();
            return "faild";
        }
        HttpsURLConnection conn = null;
        String str = "";
        try {
            conn = (HttpsURLConnection) new URL(url).openConnection();
            conn.setDoInput(true);// 打开输入流,以便从服务器获取数据
            conn.setDoOutput(true);// 打开输出流,以便向服务器提交数据
            conn.setConnectTimeout(30000); // 设置连接超时时间
            conn.setReadTimeout(30000); //设置返回超时时间,下面要对超时进行处理
            conn.setRequestMethod("POST");
            conn.setUseCaches(false);// 使用Post方式不能使用缓存
            conn.setInstanceFollowRedirects(true);
            //conn.setRequestProperty("Cookie", SessionId);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            conn.connect();
            DataOutputStream out = new DataOutputStream(conn.getOutputStream());
            out.writeBytes(content);
            out.flush();
            out.close(); // flush and close
            int response = conn.getResponseCode(); // 获得服务器的响应码
            if (response == HttpURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), encoding));
                StringBuffer sb = new StringBuffer();
                String line;
                while ((line = br.readLine()) != null) {
                    line = new String(line.getBytes(), "UTF-8");
                    sb.append(line);
                }
                str = sb.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            //里面会抛连接和返回超时java.net.SocketTimeoutException,还有IO异常
            return "faild";
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        return str;
    }

    public static String HttpsGet(String url, String encoding) {
        LogUtils.i("HttpUtils", "httpsget url: " + url + " encoding: " + encoding);
        SSLContext sc = null;
        try {
            sc = SSLContext.getInstance("TLS");
            MyTrustManager mtm = new MyTrustManager();
            sc.init(null, new TrustManager[]{mtm}, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "faild";
        } catch (KeyManagementException e) {
            e.printStackTrace();
            return "faild";
        }
        HttpsURLConnection conn = null;
        String str = "";
        try {
            conn = (HttpsURLConnection) new URL(url).openConnection();
            conn.setDoInput(true);// 打开输入流,以便从服务器获取数据
            conn.setDoOutput(true);// 打开输出流,以便向服务器提交数据
            conn.setConnectTimeout(30000); // 设置连接超时时间
            conn.setReadTimeout(30000); //设置返回超时时间,下面要对超时进行处理
            conn.setRequestMethod("GET");
            conn.connect();
            int response = conn.getResponseCode(); // 获得服务器的响应码
            if (response == HttpURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), encoding));
                StringBuffer sb = new StringBuffer();
                String line;
                while ((line = br.readLine()) != null) {
                    line = new String(line.getBytes(), "UTF-8");
                    sb.append(line);
                }
                str = sb.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            //里面会抛连接和返回超时java.net.SocketTimeoutException,还有IO异常
            return "faild";
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        return str;
    }

    /**
     * 获取基本信息
     *
     * @return
     */
    public static StringBuffer getConstansData() {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(Constants.order_from);//向服务器传递版本号

        stringBuffer.deleteCharAt(stringBuffer.length() - 1);
        return stringBuffer;
    }

    /**
     *  封装请求体信息
     *  @params 请求体内容,
     *  @encode 编码格式
    */
    public static StringBuffer getRequestData(Map<String, String> params, String encode) {
        StringBuffer stringBuffer = getConstansData(); // 存储封装好的请求体信息
        stringBuffer.append("&");
        try {
            if (params != null && params.size() > 0) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    String key = entry.getKey();
                    String value = entry.getValue();
                    if (!TextUtils.isEmpty(key)) {
                        stringBuffer.append(key)
                                .append("=")
                                .append(URLEncoder.encode((TextUtils.isEmpty(value) ? "" : value), encode))
                                .append("&");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        stringBuffer.deleteCharAt(stringBuffer.length() - 1); // 删除最后的一个"&"
        LogUtils.i("", stringBuffer.toString());
        return stringBuffer;
    }

    static class MyTrustManager implements X509TrustManager {

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {

        }

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

        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    }

    /**
     * 服务器下载文件
     *
     * @param fileDir  文件保存路径
     * @param fileName 文件名称
     * @param url_     下载路径
     * @return
     */
    public static boolean downLoadingFile(String fileDir, String fileName, String url_) {
        boolean flag = false;
        HttpURLConnection conn = null;
        FileUtils fileUtils = new FileUtils();
        try {
            conn = (HttpURLConnection) (new URL(url_)).openConnection();
            conn.setRequestMethod("GET");
            conn.setReadTimeout(10 * 1000);
            conn.getDoInput();
            conn.getDoOutput();
            conn.connect();
            if (conn.getResponseCode() == 200) {
                File file = fileUtils.write2SDFromInput(fileDir, fileName, conn.getInputStream());
                if (file != null) {
                    flag = true;
                } else {
                    flag = false;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            flag = false;
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        return flag;
    }

}
时间: 2024-10-27 07:24:53

工具类总结---(六)---之http及https请求的相关文章

Java生成证书工具类 InstallCert.java解决httpClient访问https出错:PKIX path building failed

编译:javac InstallCert.java运行:java InstallCert 要访问的网址 最后面会输出: Enter certificate to add to trusted keystore or 'q' to quit: [1] 输入1,然后直接回车,会在相应的目录下产生一个名为'jssecacerts'的证书.将证书copy到$JAVA_HOME/jre/lib/security目录下 InstallCert.java /* * Copyright 2006 Sun Mic

Java并发(十六):并发工具类——Exchanger

Exchanger(交换者)是一个用于线程间协作的工具类.Exchanger用于进行线程间的数据交换.它提供一个同步点,在这个同步点两个线程可以交换彼此的数据.这两个线程通过exchange方法交换数据, 如果第一个线程先执行exchange方法,它会一直等待第二个线程也执行exchange,当两个线程都到达同步点时,这两个线程就可以交换数据,将本线程生产出来的数据传递给对方. 举例 class ExchangerTest { static class Producer implements R

Hutools之http工具类

Hutools请求网络资源使用的工具类:HttpRequest和HttpResponse Get方式请求数据 Get方式请求数据Map<String,Object> paramMap = new HashMap<>(); //map中带不带参数都可以这样用 HttpResponse httpResponse = HttpRequest.get(url).form(paramMap).timeout(time * 1000).execute(); int status = httpR

微信小程序工具类

wechat-common-sdk ? 场景:目前工作中的项目需要包含并使用另一个项目. 也许是第三方库,或者你独立开发的,用于多个父项目的库. 现在问题来了:你想要把它们当做两个独立的项目,同时又想在一个项目中使用另一个. 我们举一个例子. 假设你正在开发一个网站然后创建了 Atom 订阅. 你决定使用一个库,而不是写自己的 Atom 生成代码. 你可能不得不通过 CPAN 安装或 Ruby gem 来包含共享库中的代码,或者将源代码直接拷贝到自己的项目中. 如果将这个库包含进来,那么无论用何

java:工具类

Google guava工具类的介绍和使用:https://blog.csdn.net/wwwdc1012/article/details/82228458 Apache Commons 工具类介绍及简单使用:https://www.cnblogs.com/koal/p/5161743.html Json详解以及fastjson使用教程:https://blog.csdn.net/srj1095530512/article/details/82529759 原文地址:https://www.cn

java 微信开发的工具类WeChatUtils

import com.alibaba.fastjson.JSONObject;import com.bhudy.entity.BhudyPlugin;import com.bhudy.service.BhudyPluginService;import org.jdom2.Document;import org.jdom2.Element;import org.jdom2.JDOMException;import org.jdom2.input.SAXBuilder;import org.spri

Spring3中好用的工具类收集

1) 请求工具类 org.springframework.web.bind.ServletRequestUtils //取请求参数的整数值: public static Integer getIntParameter(ServletRequest request, String name) public static int getIntParameter(ServletRequest request, String name, int defaultVal) -->单个值 public sta

Spring 常用工具类

1) 请求工具类 org.springframework.web.bind.ServletRequestUtils //取请求参数的整数值: public static Integer getIntParameter(ServletRequest request, String name) public static int getIntParameter(ServletRequest request, String name, int defaultVal) -->单个值 public sta

httpclient绕过证书验证进行HTTPS请求

http请求是我们常用的一种web应用的应用层协议,但是由于它的不安全性,现在正在逐渐向https协议过渡.https协议是在http的基础上进行了隧道加密,加密方式有SSL和TLS两种.当server用https协议进行数据交换后,client请求server时会对server的证书进行校验,如果server端证书为四大证书机构颁发的证书或者其授权机构颁发的证书,则允许进一步请求,否则会警告证书不受信任.更多信息可参考https://www.cnblogs.com/handsomeBoys/p

捕获异常、存sd卡、封装请求头体、加密map值、网络工具类、生成Json、Https协议、传log日志到服务器、app崩溃友好重启

点击打开链接,免积分下载 在集成了统计SDK(友盟统计,百度统计等)之后,有一个非常有利于测试的功能:错误分析!此功能能够将程序在运行中碰到的崩溃(runtimeException)问题反馈到服务器,帮助开发者改善产品,多适配机器.然而在公司android开发中不集成这些SDK,那应该怎么实现这样的功能呢?下面让我们来看下如何使用UncaughtExceptionHandler来捕获异常. 在Android开发中,常常会出现uncheched Exception 导致程序的crash,为了提供良