Android Http請求

cryAllen發表於2015-04-13

Android HTTP請求封裝程式碼

/**
 * This class is the Utils of other classes.
 */
public class HttpUtil {
    /** 變數/常量說明 */
    private static final String TAG              = "HttpUtils";
    /** 超時時間 */
    private static int          mTimeOut         = 20000;
    /** 私鑰密碼 */
    /** 使用協議 */
    private static final String CLIENT_AGREEMENT = "TLS";
    /** 金鑰管理器 */
    /** 變數/常量說明 */
    private static HttpUtil     mHttpUtils       = null;

    /**
     * 獲取HPPS物件例項
     * 
     * @param application
     * @return
     * @since V1.0
     */
    public static HttpUtil getInstace(Context context) {
        if (mHttpUtils == null) {
            mHttpUtils = new HttpUtil(context);
        }
        return mHttpUtils;
    }

    /**
     * @param application
     */
    private HttpUtil(Context context) {
    }

    /**
     * 這裡對方法做描述
     * 
     * @param servAddr
     * @param xmlBody
     * @return
     * @throws HttpException
     * @since V1.0
     */
    public String httpGetRequest(String servAddr) throws HttpException {
        // create connection
        String response = null;
        HttpURLConnection conn = null;
        boolean ret = false;
        InputStream in = null;

        try {
            URL url = new URL(servAddr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(mTimeOut);
            conn.setReadTimeout(mTimeOut);
            conn.setDoInput(true);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Content-type", "text/xml; charset=utf-8");

            if (conn.getResponseCode() == 200) {
                // getCookie(conn);
                in = new BufferedInputStream(conn.getInputStream());
            } else {
                in = new BufferedInputStream(conn.getErrorStream());
            }

            response = inputStream2String(in);

            in.close();
            in = null;
            ret = true;
        } catch (MalformedURLException e) {
            ret = false;
            e.printStackTrace();
        } catch (ProtocolException e) {
            ret = false;
            e.printStackTrace();
        } catch (IOException e) {
            ret = false;
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                in = null;
            }
            if (conn != null) {
                // 斷開連線
                conn.disconnect();
                conn = null;
            }
        }

        // 丟擲異常
        if (!ret) {
            throw new HttpException("network exception", HttpException.HTTP_NETWORD_EXCEPTION);
        }

        return response;
    }

    /**
     * 這裡對方法做描述
     * 
     * @return
     * @throws InvalidFormatException
     * @see
     * @since V1.0
     */
    public static String httpPostRequest(String path) {
        // create connection
        String response = null;
        HttpURLConnection conn = null;
        try {
            URL url = new URL(path);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(mTimeOut);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-type", "text/xml; charset=utf-8");

            InputStream in = new BufferedInputStream(conn.getInputStream());
            response = inputStream2String(in);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                // 斷開連線
                conn.disconnect();
                conn = null;
            }
        }

        return response;
    }

    /**
     * httpPost方式
     * 
     * @param servAddr
     * @param xmlBody
     * @return
     * @throws HttpException
     * @since V1.0
     */
    public String httpPostRequest(String servAddr, String xmlBody) throws HttpException {
        // create connection
        String response = null;
        HttpURLConnection conn = null;
        boolean ret = false;
        InputStream in = null;
        DataOutputStream os = null;
        try {
            URL url = new URL(servAddr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(mTimeOut);
            conn.setReadTimeout(mTimeOut);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-type", "text/xml; charset=utf-8");

            // send xml contant to server
            os = new DataOutputStream(conn.getOutputStream());
            os.write(xmlBody.getBytes(), 0, xmlBody.getBytes().length);
            os.flush();
            os.close();
            os = null;
            if (conn.getResponseCode() == 200) {
                // getCookie(conn);
                in = new BufferedInputStream(conn.getInputStream());
            } else {
                in = new BufferedInputStream(conn.getErrorStream());
            }

            response = inputStream2String(in);

            in.close();
            in = null;
            ret = true;
        } catch (MalformedURLException e) {
            ret = false;
            e.printStackTrace();
        } catch (ProtocolException e) {
            ret = false;
            e.printStackTrace();
        } catch (IOException e) {
            ret = false;
            e.printStackTrace();
        } finally {

            try {
                if (in != null) {
                    in.close();
                }
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            in = null;

            if (conn != null) {
                // 斷開連線
                conn.disconnect();
                conn = null;
            }
        }

        // 丟擲異常
        if (!ret) {
            throw new HttpException("network exception", HttpException.HTTP_NETWORD_EXCEPTION);
        }

        return response;
    }

    /**
     * 這裡對方法做描述
     * 
     * @return
     * @throws HttpException
     * @see
     * @since V1.0
     */
    public String httpsGetRequest(String servHttpsAddr) {
        if (servHttpsAddr == null || servHttpsAddr.equals("")) {
            CLog.d(TAG, "sslGetRequest servHttpsAddr == null");
            return "";
        }

        boolean bRet = verifyHttpsUrl(servHttpsAddr);
        if (!bRet) {
            CLog.d(TAG, "sslGetRequest verifyHttpsUrl fail");
            return "";
        }

        String response = "";
        try {
            response = getSslRequest(servHttpsAddr);
        } catch (HttpException e) {
            e.printStackTrace();
            CLog.d(TAG, "sslGetRequest verifyHttpsUrl fail");
            return "";
        }

        return response;
    }

    /**
     * httpsPost方式傳送
     * 
     * @return
     * @throws HttpException
     * @see
     * @since V1.0
     */
    public String httpsPostRequest(String servHttpsAddr, String xmlBody) {
        if (servHttpsAddr == null || servHttpsAddr.equals("")) {
            CLog.d(TAG, "postHttpsRequest servHttpsAddr == null");
            return "";
        }

        if (xmlBody == null || xmlBody.equals("")) {
            CLog.d(TAG, "postHttpsRequest xmlBody == null");
            return "";
        }

        boolean bRet = verifyHttpsUrl(servHttpsAddr);
        if (!bRet) {
            CLog.d(TAG, "postHttpsRequest verifyHttpsUrl fail");
            return "";
        }

        String response = "";
        try {
            response = postSslRequest(servHttpsAddr, xmlBody);
        } catch (HttpException e) {
            e.printStackTrace();
            CLog.d(TAG, "postHttpsRequest postSslRequest fail");
            return "";
        }

        return response;
    }

    /**
     * 把輸入流轉化成string
     * 
     * @param is
     * @return
     * @see
     * @since V1.0
     */
    private static String inputStream2String(InputStream is) {
        InputStreamReader inputStreamReader = new InputStreamReader(is);
        BufferedReader in = new BufferedReader(inputStreamReader);
        StringBuffer buffer = new StringBuffer();
        String line = "";
        try {
            while ((line = in.readLine()) != null) {
                buffer.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            try {
                if (inputStreamReader != null) {
                    inputStreamReader.close();
                }
                inputStreamReader = null;
                if (in != null) {
                    in.close();
                }
                in = null;
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return buffer.toString();
    }

    /**
     * 這裡對方法做描述
     * 
     * @param servHttpsAddr
     * @param xmlBody
     * @return
     * @throws HttpException
     * @since V1.0
     */
    private String getSslRequest(String servHttpsAddr) throws HttpException {
        // create connection
        String response = null;
        HttpURLConnection conn = null;
        boolean ret = false;
        InputStream in = null;
        try {
            URL url = new URL(servHttpsAddr);
            trustAllHosts();
            conn = (HttpsURLConnection) url.openConnection();
            ((HttpsURLConnection) conn).setHostnameVerifier(DO_NOT_VERIFY);// 不進行主機名確認

            // ((HttpsURLConnection)
            // conn).setSSLSocketFactory(getPushSSLSocketFactory());

            conn.setConnectTimeout(mTimeOut);
            conn.setReadTimeout(mTimeOut);
            conn.setDoInput(true);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Content-type", "text/xml; charset=utf-8");

            if (conn.getResponseCode() == 200) {
                // getCookie(conn);
                in = new BufferedInputStream(conn.getInputStream());
            } else {
                in = new BufferedInputStream(conn.getErrorStream());
            }

            response = inputStream2String(in);

            in.close();
            in = null;
            ret = true;
        } catch (MalformedURLException e) {
            ret = false;
            e.printStackTrace();
        } catch (ProtocolException e) {
            ret = false;
            e.printStackTrace();
        } catch (IOException e) {
            ret = false;
            e.printStackTrace();
        }
        // catch (NoSuchAlgorithmException e) {
        // ret = false;
        // e.printStackTrace();
        // } catch (KeyManagementException e) {
        // ret = false;
        // e.printStackTrace();
        // } catch (KeyStoreException e) {
        // ret = false;
        // e.printStackTrace();
        // } catch (CertificateException e) {
        // ret = false;
        // e.printStackTrace();
        // } catch (UnrecoverableKeyException e) {
        // ret = false;
        // e.printStackTrace();
        // }
        finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                in = null;
            }
            if (conn != null) {
                // 斷開連線
                conn.disconnect();
                conn = null;
            }
        }

        // 丟擲異常
        if (!ret) {
            throw new HttpException("network exception", HttpException.HTTP_NETWORD_EXCEPTION);
        }

        return response;
    }

    /**
     * 驗證https地址
     * 
     * @since V1.0
     */
    public boolean verifyHttpsUrl(String httpsAddr) {
        // TODO Auto-generated method stub
        if (httpsAddr == null || httpsAddr.equals("")) {
            CLog.e(TAG, "verifyHttpsUrl httpsAddr == null");
            return false;
        }

        URL httpsUurl;
        try {
            httpsUurl = new URL(httpsAddr);
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            CLog.e(TAG, "verifyHttpsUrl httpsAddr not url, error url:" + httpsAddr);
            return false;
        }

        if (!httpsUurl.getProtocol().equalsIgnoreCase("https")) {
            CLog.e(TAG, "verifyHttpsUrl httpsAddr not https, error url:" + httpsAddr);
            return false;
        }

        return true;
    }

    /**
     * post ssl請求
     * 
     * @param servHttpsAddr
     * @param xmlBody
     * @return
     * @throws HttpException
     * @since V1.0
     */
    private String postSslRequest(String servHttpsAddr, String xmlBody) throws HttpException {
        // 回覆信令
        String response = null;
        //
        boolean ret = false;
        // 輸入流
        InputStream in = null;
        DataOutputStream os = null;
        HttpsURLConnection httpsConn = null;
        InputStream inputStream = null;
        try {
            URL url = new URL(servHttpsAddr);

            // solution: javax.net.ssl.SSLException: Not trusted server
            // certificate
            trustAllHosts();

            // 開啟連線
            httpsConn = (HttpsURLConnection) url.openConnection();
            // 不進行主機名確認
            httpsConn.setHostnameVerifier(DO_NOT_VERIFY);
            httpsConn.setConnectTimeout(mTimeOut);
            httpsConn.setReadTimeout(mTimeOut);
            httpsConn.setDoInput(true);
            httpsConn.setDoOutput(true);
            httpsConn.setRequestMethod("POST");
            httpsConn.setRequestProperty("Content-type","text/xml; charset=utf-8");

            // send xml contant to server
            os = new DataOutputStream(httpsConn.getOutputStream());
            os.write(xmlBody.getBytes(), 0, xmlBody.getBytes().length);
            os.flush();
            os.close();
            os = null;

            if (httpsConn.getResponseCode() == 200) {
                // getCookie(conn);
                inputStream = httpsConn.getInputStream();
                in = new BufferedInputStream(inputStream);
            } else {
                inputStream = httpsConn.getErrorStream();
                in = new BufferedInputStream(inputStream);
            }

            response = inputStream2String(in);
            if (inputStream != null) {
                inputStream.close();
                inputStream = null;
            }

            in.close();
            in = null;
            ret = true;
        } catch (MalformedURLException e) {
            ret = false;
            e.printStackTrace();
        } catch (ProtocolException e) {
            ret = false;
            e.printStackTrace();
        } catch (IOException e) {
            ret = false;
            e.printStackTrace();
        } finally {

            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (in != null) {
                    in.close();
                }
                in = null;
                if (os != null) {
                    os.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }

            if (httpsConn != null) {
                // 斷開連線
                httpsConn.disconnect();
                httpsConn = null;
            }
        }

        // 丟擲異常
        if (!ret) {
            throw new HttpException("network exception", HttpException.HTTP_NETWORD_EXCEPTION);
        }

        return response;
    }

    /** always verify the host - dont check for certificate */
    final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
                                                    public boolean verify(String hostname, SSLSession session) {
                                                        return true;
                                                    }
                                                };

    /**
     * Trust every server - dont check for any certificate
     * 
     * @since V1.0
     */
    private static void 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[] chain, String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }
        } };

        // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance(CLIENT_AGREEMENT);
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 在此對類做相應的描述 */
    public static class _FakeX509TrustManager implements X509TrustManager {

        /** 變數/常量說明 */
        private static TrustManager[]          trustManagers;
        /** 變數/常量說明 */
        private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {};

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

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

        /**
         * 這裡對方法做描述
         * 
         * @param chain
         * @return
         * @since V1.0
         */
        public boolean isClientTrusted(X509Certificate[] chain) {
            return true;
        }

        /**
         * 這裡對方法做描述
         * 
         * @param chain
         * @return
         * @since V1.0
         */
        public boolean isServerTrusted(X509Certificate[] chain) {
            return true;
        }

        /*
         * (non-Javadoc)
         * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers()
         */
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return _AcceptedIssuers;
        }

        /**
         * 這裡對方法做描述
         * 
         * @since V1.0
         */
        public static void allowAllSSL() {
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }

            });

            SSLContext context = null;
            if (trustManagers == null) {
                trustManagers = new TrustManager[] { new _FakeX509TrustManager() };
            }

            try {
                context = SSLContext.getInstance(CLIENT_AGREEMENT);
                if (context == null) {
                    return;
                }
                context.init(null, trustManagers, new SecureRandom());
                SSLSocketFactory defaultSSLSocketFactory = context.getSocketFactory();
                if (defaultSSLSocketFactory != null) {
                    HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
                }
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (KeyManagementException e) {
                e.printStackTrace();
            }

        }
    }
}

 

相關文章