Newer
Older
dxcgt / app / src / main / java / com / smartdot / cgt / util / HttpRequestTools.java
wangxitong on 6 Apr 2021 15 KB first commit
package com.smartdot.cgt.util;

import com.smartdot.cgt.request.DownLoadingProgress;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.ByteArrayBuffer;
import org.apache.http.util.EncodingUtils;

public class HttpRequestTools {

    /**
     * 通过GET方法获取类型为String的返回值
     * 
     * @param url
//     * @param downLoadingProgress进度控制管理器
//     * @param handlerStatus进度控制标识
     * @return 获取到的字符串
     * @throws IOException
     */
    public static String getReturnString(String url, DownLoadingProgress downLoadingProgress, int handlerStatus)
        throws IOException {

        String encodingType = ApplicationMain.getInstance().getCgtConfig().getUploadEncoding();

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        get(url, outputStream, downLoadingProgress, handlerStatus);

        outputStream.close();

        return EncodingUtils.getString(outputStream.toByteArray(), encodingType);
    }

    public static String getwithToken(String url, String token,DownLoadingProgress downLoadingProgress, int handlerStatus)
            throws IOException {

        String encodingType = ApplicationMain.getInstance().getCgtConfig().getUploadEncoding();

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        get(url, token, outputStream, downLoadingProgress, handlerStatus);

        outputStream.close();

        return EncodingUtils.getString(outputStream.toByteArray(), encodingType);
    }

    /**
     * 通过POST方法获取类型为String的返回值
     * 
     * @param url
     * @param postString
//     * @param downLoadingProgress进度控制管理器
//     * @param handlerStatus进度控制标识
     * @return 获取到的字符串
     * @throws IOException
     */
    public static String postReturnString(String url, String postString, DownLoadingProgress downLoadingProgress,
            int handlerStatus) throws IOException {

        String encodingType = ApplicationMain.getInstance().getCgtConfig().getUploadEncoding();

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        post(url, postString, outputStream, downLoadingProgress, handlerStatus);

        outputStream.close();

        return EncodingUtils.getString(outputStream.toByteArray(), encodingType);
    }

    public static String postReturnString(String token, String url, String postString, DownLoadingProgress downLoadingProgress,
                                          int handlerStatus) throws IOException {

        String encodingType = ApplicationMain.getInstance().getCgtConfig().getUploadEncoding();

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        post(token, url, postString, outputStream, downLoadingProgress, handlerStatus);

        outputStream.close();

        return EncodingUtils.getString(outputStream.toByteArray(), encodingType);
    }

    /**
     * 通过POST方法上传文件等并获取服务器返回的字符串
     * 
     * @param url
     * @param byteArray
     * @param downLoadingProgress
     *            进度控制管理器
     * @param handlerStatus
     *            进度控制标识
     * @return
     * @throws IOException
     */
    public static String postBytesReturnString(String url, byte[] byteArray, DownLoadingProgress downLoadingProgress,
            int handlerStatus) throws IOException {

        String encodingType = ApplicationMain.getInstance().getCgtConfig().getUploadEncoding();

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        postBytes(url, byteArray, outputStream, downLoadingProgress, handlerStatus);

        outputStream.close();

        return EncodingUtils.getString(outputStream.toByteArray(), encodingType);
    }

    /**
     * 通过GET方法获取服务器返回stream,并存入outputStream
     * 
     * @param url
     * @param outputStream
     * @param downLoadingProgress
     *            进度控制管理器
     * @param handlerStatus
     *            进度控制标识
     * @throws IOException
     */
    public static void get(String url, OutputStream outputStream, DownLoadingProgress downLoadingProgress, int handlerStatus) throws IOException {
        request(url, "GET", null, null, outputStream, downLoadingProgress, handlerStatus);
    }

    public static void get(String url, String token,OutputStream outputStream, DownLoadingProgress downLoadingProgress, int handlerStatus) throws IOException {
        request(url, token, "GET", null, null, outputStream, downLoadingProgress, handlerStatus);
    }
    /**
     * 通过POST方法获取服务器返回stream,并存入outputStream
     * 
     * @param url
     * @param postString
     * @param outputStream
     * @param downLoadingProgress
     *            进度控制管理器
     * @param handlerStatus
     *            进度控制标识
     * @throws IOException
     */
    public static void post(String url, String postString, OutputStream outputStream,
            DownLoadingProgress downLoadingProgress, int handlerStatus) throws IOException {
        byte[] requestBytes = null;
        if (!StringUtils.isNullOrEmpty(postString)) {
            requestBytes = postString.getBytes(HTTP.UTF_8);
        }
        request(url, "POST", requestBytes, null, outputStream, downLoadingProgress, handlerStatus);
    }

    public static void post(String token, String url, String postString, OutputStream outputStream,
                            DownLoadingProgress downLoadingProgress, int handlerStatus) throws IOException {
        byte[] requestBytes = null;
        if (!StringUtils.isNullOrEmpty(postString)) {
            requestBytes = postString.getBytes(HTTP.UTF_8);
        }
        request(url, token, "POST", requestBytes, null, outputStream, downLoadingProgress, handlerStatus);
    }

    /**
     * 通过POST方法上传文件等并获取服务器返回stream,存入outputStream
     * 
     * @param url
     * @param byteArray
     * @param outputStream
     * @param downLoadingProgress
     * @param handlerStatus
     * @throws IOException
     */
    public static void postBytes(String url, byte[] byteArray, OutputStream outputStream,
            DownLoadingProgress downLoadingProgress, int handlerStatus) throws IOException {

        String boundary = "----------" + Long.toHexString(new Date().getTime());

        StringBuilder sb = new StringBuilder();
        sb.append("--");
        sb.append(boundary);
        sb.append("\r\n");
        sb.append("Content-Disposition: form-data; name=\"upload\";filename=\"uploadfilename\"");
        sb.append("\r\n");
        sb.append("Content-Type:application/octet-stream");
        sb.append("\r\n");
        sb.append("\r\n");

        String postHeader = sb.toString();
        byte[] postHeaderBytes = postHeader.getBytes(HTTP.UTF_8);
        byte[] boundaryBytes = ("\r\n--" + boundary + "--\r\n").getBytes(HTTP.UTF_8);

        int capacity=postHeaderBytes.length+byteArray.length+boundaryBytes.length;
        ByteArrayBuffer byteArrayBuffer = new ByteArrayBuffer(capacity);
        byteArrayBuffer.append(postHeaderBytes, 0, postHeaderBytes.length);
        byteArrayBuffer.append(byteArray, 0, byteArray.length);
        byteArrayBuffer.append(boundaryBytes, 0, boundaryBytes.length);

        request(url, "POST", byteArrayBuffer.toByteArray(), boundary, outputStream, downLoadingProgress, handlerStatus);

    }

    /**
     * http请求的基础方法,一般不直接调用该方法
     * 
     * @param url
     * @param requestBytes
     * @param requestMethod
     * @param boundary
     * @param outputStream
     * @param downLoadingProgress
     * @param handlerStatus
     * @throws IOException
     */
    public static void request(String url, String requestMethod, byte[] requestBytes, String boundary,
                               OutputStream outputStream, DownLoadingProgress downLoadingProgress, int handlerStatus) throws IOException {

        HttpURLConnection conn = null;
        InputStream inputStream = null;
        try {
            URL requestUrl = new URL(url);
            conn = (HttpURLConnection) requestUrl.openConnection();
            if (requestMethod.equals(HttpPost.METHOD_NAME)) {
                conn.setDoOutput(true);
                conn.setRequestMethod(requestMethod);
            }
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(600000);
            if (!StringUtils.isNullOrEmpty(boundary)) {
                conn.setRequestProperty("Connection", "keep-alive");
                conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            } else {
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            }
            if (requestBytes != null && requestBytes.length > 0) {
                conn.setRequestProperty("Content-Length", "" + requestBytes.length);
            }

            conn.connect();

            if (requestBytes != null && requestBytes.length > 0) {
                OutputStream requestOutputStream = conn.getOutputStream();
                requestOutputStream.write(requestBytes);
                requestOutputStream.flush();
                requestOutputStream.close();
            }

            if (conn.getResponseCode() == HttpStatus.SC_OK || conn.getResponseCode() == HttpStatus.SC_CREATED) {
                inputStream = conn.getInputStream();
                byte[] b = new byte[1024];
                int len = inputStream.read(b);
                int readedCount = len;
                while (len != -1) {
                    outputStream.write(b, 0, len);
                    if (downLoadingProgress != null) {
                        int totalCount = conn.getContentLength();
                        if (totalCount <= 0) {
                            int unReadedCount = -1;
                            try {
                                Field bytesRemainingField = inputStream.getClass().getDeclaredField("bytesRemaining");
                                bytesRemainingField.setAccessible(true);
                                unReadedCount = bytesRemainingField.getInt(inputStream);
                            } catch (SecurityException e) {
                                e.printStackTrace();
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            } catch (IllegalArgumentException e) {
                                e.printStackTrace();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                            if (unReadedCount < inputStream.available()) {
                                unReadedCount = inputStream.available();
                            }
                            totalCount = readedCount + unReadedCount;
                        }
                        downLoadingProgress.onProgressUpdate(readedCount * 100 / totalCount, handlerStatus);
                    }
                    len = inputStream.read(b);
                    readedCount += len;
                }
                outputStream.flush();
                inputStream.close();
            }
        } catch (IOException e1) {
            throw e1;
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    }

    public static void request(String url, String token, String requestMethod, byte[] requestBytes, String boundary,
                               OutputStream outputStream, DownLoadingProgress downLoadingProgress, int handlerStatus) throws IOException {

        HttpURLConnection conn = null;
        InputStream inputStream = null;
        try {
            URL requestUrl = new URL(url);
            conn = (HttpURLConnection) requestUrl.openConnection();
            if (requestMethod.equals(HttpPost.METHOD_NAME)) {
                conn.setDoOutput(true);
                conn.setRequestMethod(requestMethod);
            }
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(600000);
            if (!StringUtils.isNullOrEmpty(boundary)) {
                conn.setRequestProperty("Connection", "keep-alive");
                conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            } else {
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            }
            if (requestBytes != null && requestBytes.length > 0) {
                conn.setRequestProperty("Content-Length", "" + requestBytes.length);
            }
            if(!StringUtils.isNullOrEmpty(token)){
                conn.setRequestProperty("token", "" + token);
            }

            conn.connect();

            if (requestBytes != null && requestBytes.length > 0) {
                OutputStream requestOutputStream = conn.getOutputStream();
                requestOutputStream.write(requestBytes);
                requestOutputStream.flush();
                requestOutputStream.close();
            }

            if (conn.getResponseCode() == HttpStatus.SC_OK || conn.getResponseCode() == HttpStatus.SC_CREATED) {
                inputStream = conn.getInputStream();
                byte[] b = new byte[1024];
                int len = inputStream.read(b);
                int readedCount = len;
                while (len != -1) {
                    outputStream.write(b, 0, len);
                    if (downLoadingProgress != null) {
                        int totalCount = conn.getContentLength();
                        if (totalCount <= 0) {
                            int unReadedCount = -1;
                            try {
                                Field bytesRemainingField = inputStream.getClass().getDeclaredField("bytesRemaining");
                                bytesRemainingField.setAccessible(true);
                                unReadedCount = bytesRemainingField.getInt(inputStream);
                            } catch (SecurityException e) {
                                e.printStackTrace();
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            } catch (IllegalArgumentException e) {
                                e.printStackTrace();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                            if (unReadedCount < inputStream.available()) {
                                unReadedCount = inputStream.available();
                            }
                            totalCount = readedCount + unReadedCount;
                        }
                        downLoadingProgress.onProgressUpdate(readedCount * 100 / totalCount, handlerStatus);
                    }
                    len = inputStream.read(b);
                    readedCount += len;
                }
                outputStream.flush();
                inputStream.close();
            }
        } catch (IOException e1) {
            throw e1;
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    }


}