Android HttpsURLConnection get、post 访问网络

来源:互联网 发布:李霖丰淘宝店不做了吗 编辑:程序博客网 时间:2024/06/04 22:35
证书验证类,此处默认通过所有证书
HttpUtils 类
public class HttpUtils {    public static void trustAllHosts() {        final String TAG = "trustAllHosts";        // Create a trust manager that does not validate certificate chains        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {            public java.security.cert.X509Certificate[] getAcceptedIssuers() {                return new java.security.cert.X509Certificate[] {};            }            public void checkClientTrusted(X509Certificate[] chainString authType) throws CertificateException {                LogF.i(TAG"checkClientTrusted");            }            public void checkServerTrusted(X509Certificate[] chainString authType) throws CertificateException {                LogF.i(TAG"checkServerTrusted");            }        } };        // Install the all-trusting trust manager        try {            SSLContext sc = SSLContext.getInstance("TLS");            sc.init(null, trustAllCerts, new java.security.SecureRandom());            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());        catch (Exception e) {            e.printStackTrace();        }    }
}
final static HostnameVerifier DO_NOT_VERIFY new HostnameVerifier() {    public boolean verify(String hostnameSSLSession session) {        return true;    }};
1、get 请求

    /**     * get方式请求服务器     *     * @param param 请求时包含的参数     * @return     */    public static String get(RequestParam param) throws IOExceptionServerException {        String urlString = param.getUrl();        if (TextUtils.isEmpty(urlString))            return null;
        HttpURLConnection httpURLConnection = null;
        HttpsURLConnection https = null;
        BufferedReader bufferedReader = null;        try {
            URL url = new URL(urlString);
            HttpUtils.trustAllHosts();
            // 打开连接
            if (url.getProtocol().toLowerCase().equals("https")) {
                https = (HttpsURLConnection) url.openConnection();
                https.setHostnameVerifier(DO_NOT_VERIFY);
                httpURLConnection = https;
            } else {
                httpURLConnection = (HttpURLConnection) url.openConnection();
            }
            //设置读取超时
            //设置连接超时            httpURLConnection.setReadTimeout(10 1000);            httpURLConnection.setConnectTimeout(1000);            // Set the post method. Default is GET            httpURLConnection.setRequestMethod("GET");            httpURLConnection.connect();            if (httpURLConnection.getResponseCode() == 200) {                bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()"UTF-8"));                StringBuffer stringBuffer = new StringBuffer();                String lineStr = "";                while ((lineStr = bufferedReader.readLine()) != null) {                    stringBuffer.append(lineStr + "\n");                }                return stringBuffer.toString();            else {                Log.w("HTTP""请求服务器异常 " + httpURLConnection.getResponseCode());                throw new ServerException("服务器异常:" + httpURLConnection.getResponseCode());            }        } finally {            if(bufferedReader != null)                bufferedReader.close();            if(httpURLConnection != null)
                httpURLConnection.disconnect();
            if(https != null)
                https.disconnect();
        }
    }

2、post 请求

    /**     * post 方式请求服务器     *     * @param param 请求参数     * @return 响应 json 串     * @throws IOException 文本异常,超时等     */    public static String post(RequestParam param) throws IOExceptionServerException {        String urlString = param.getUrl();        if (TextUtils.isEmpty(urlString))            return null;
        HttpURLConnection httpURLConnection = null;
        HttpsURLConnection https = null;
        OutputStreamWriter outputStreamWriter = null;        BufferedReader bufferedReader = null;        try {            //url            URL url = new URL(urlString);
            HttpUtils.trustAllHosts();
            // 打开连接
            if (url.getProtocol().toLowerCase().equals("https")) {
                https = (HttpsURLConnection) url.openConnection();
                https.setHostnameVerifier(DO_NOT_VERIFY);
                httpURLConnection = https;
            } else {
                httpURLConnection = (HttpURLConnection) url.openConnection();
            }
            //设置读取超时            //设置连接超时            httpURLConnection.setReadTimeout(10 1000);            httpURLConnection.setConnectTimeout(1000);            // Read from the connection. Default is true.            httpURLConnection.setDoInput(true);            // Output to the connection. Default is            // false, set to true because post            // method must write something to the            // connection            // 设置是否向connection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true            httpURLConnection.setDoOutput(true);            // Post cannot use caches            // Post 请求不能使用缓存            httpURLConnection.setUseCaches(false);            // Set the post method. Default is GET            httpURLConnection.setRequestMethod("POST");            // This method takes effects to            // every instances of this class.            // URLConnection.setFollowRedirects是static函数,作用于所有的URLConnection对象。            // connection.setFollowRedirects(true);            // This methods only            // takes effacts to this            // instance.            // URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数            httpURLConnection.setInstanceFollowRedirects(true);            // Set the content type to urlencoded,            // because we will write            // some URL-encoded content to the            // connection. Settings above must be set before connect!            // 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的            // 意思是正文是urlencoded编码过的form参数,下面我们可以看到我们对正文内容使用URLEncoder.encode            // 进行编码            httpURLConnection.setRequestProperty("Accept-Charset""UTF-8");            httpURLConnection.setRequestProperty("Content-Type""application/x-www-form-urlencoded");            // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,            // 要注意的是connection.getOutputStream会隐含的进行connect。            httpURLConnection.connect();//          DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());//          dataOutputStream.writeBytes(param.getParams());//          dataOutputStream.flush();//          dataOutputStream.close(); // flush and close//            outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream()"UTF-8");            outputStreamWriter.write(param.getParams());            outputStreamWriter.flush();            if (httpURLConnection.getResponseCode() == 200) {                bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()"UTF-8"));                StringBuffer stringBuffer = new StringBuffer();                String lineStr = "";                while ((lineStr = bufferedReader.readLine()) != null) {                    stringBuffer.append(lineStr + "\n");                }                return stringBuffer.toString();            else {                Log.w("HTTP""请求服务器异常 " + httpURLConnection.getResponseCode());                throw new ServerException("服务器异常:" + httpURLConnection.getResponseCode());            }        } finally {            if(bufferedReader != null)                bufferedReader.close();            if(outputStreamWriter != null)                outputStreamWriter.close();            if(httpURLConnection != null)
                httpURLConnection.disconnect();
            if(https != null)
                https.disconnect();
        }
    }

RequestParam类

/*** 描述:网络 请求参数 * @author HJK */public class RequestParam {    private String url;    private Map<String, Object> params;    public void put(String key, String value) {        if (params == null)            params = new HashMap<String, Object>();params.put(key, value);}    public String getUrl() {        return url;}    public void setUrl(String url) {        this.url = url;}    public List<NameValuePair> postParams() {        if (params == null)            return null;List<NameValuePair> param = new ArrayList<NameValuePair>();        for (String key:params.keySet())            param.add(new BasicNameValuePair(key, params.get(key)+""));        return param;}    public String getParams() {        if (params == null)            return null;StringBuffer stringBuffer = new StringBuffer();        for (String key : params.keySet()) {            stringBuffer.append(key).append("=").append(params.get(key)).append("&");}        if(stringBuffer.length()>0)            stringBuffer.deleteCharAt(stringBuffer.length()-1);        return stringBuffer.toString();}    public String toString() {        return params == null?null:params.toString();}}

ServerException类

/**
 * 描述:服务器异常
 * @author HJK
 */
public class ServerException extends Exception {

    public ServerException() {
        super();
    }

    public ServerException(String msg) {
        super(msg);
    }

    public ServerException(String msgThrowable cause) {
        super(msgcause);
    }

    public ServerException(Throwable cause) {
        super(cause);
    }
}
0 0