HttpHelper.java 6.02 KB
package com.yanzuoguang.util.helper;


import com.yanzuoguang.util.exception.HttpCodeException;
import com.yanzuoguang.util.thread.ProcessData;
import com.yanzuoguang.util.thread.RunProcess;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * HTTP请求工具类
 *
 * @author 颜佐光
 */
public class HttpHelper {

    /**
     * 链接超时
     */
    public static int HTTP_CONNNECT_TIMEOUT = 10 * 1000;
    /**
     * 读取超时
     */
    public static int HTTP_READ_TIMEOUT = 30 * 1000;

    /**
     * 发送POST请求,当请求失败时,抛出异常或返回空字符串
     *
     * @param url        目的地址
     * @param jsonString 请求参数,json字符串。
     * @return 远程响应结果
     */
    public static String post(String url, String jsonString) {
        try {
            // 打开URL连接
            java.net.HttpURLConnection httpConn = getConn(url);
            return post(httpConn, jsonString);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * 发送POST请求,当请求失败时,抛出异常或返回空字符串
     *
     * @param url        目的地址
     * @param jsonString 请求参数,json字符串。
     * @return 远程响应结果
     */
    public static String postApplicationJSON(String url, String jsonString) {
        try {
            // 打开URL连接
            java.net.HttpURLConnection httpConn = getConn(url);
            httpConn.setRequestProperty("Content-Type", "application/json");
            return post(httpConn, jsonString);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * 获取连接
     *
     * @param url
     * @return
     * @throws IOException
     */
    private static HttpURLConnection getConn(String url) throws IOException {
        // 创建URL对象
        java.net.URL connURL = new java.net.URL(url);
        // 打开URL连接
        java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) connURL.openConnection();
        // 设置通用属性
        httpConn.setRequestProperty("Accept", "*/*");
        httpConn.setRequestProperty("Connection", "Keep-Alive");
        httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
        // 设置POST方式
        httpConn.setDoInput(true);
        httpConn.setDoOutput(true);
        httpConn.setConnectTimeout(HTTP_CONNNECT_TIMEOUT);
        httpConn.setReadTimeout(HTTP_READ_TIMEOUT);
        return httpConn;
    }


    /**
     * 发送POST请求,当请求失败时,抛出异常或返回空字符串
     *
     * @param httpConn   链接信息
     * @param jsonString 请求参数,json字符串。
     * @return 远程响应结果
     */
    public static String post(HttpURLConnection httpConn, String jsonString) throws IOException {
        // 返回的结果
        StringBuilder result = new StringBuilder();
        // 读取响应输入流
        BufferedReader in = null;
        PrintWriter out = null;
        // 处理请求参数
        String params = "";
        try {
            params = jsonString;
            // 获取HttpURLConnection对象对应的输出流
            out = new PrintWriter(httpConn.getOutputStream());
            // 发送请求参数
            out.write(params);
            // flush输出流的缓冲
            out.flush();
            in = readStream(httpConn.getInputStream(), result);
        } catch (Exception ex) {
            in = readStream(httpConn.getErrorStream(), result);
            throw new HttpCodeException(StringHelper.toString(httpConn.getResponseCode()), ex.getMessage(), result.toString(), ex);
        } finally {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        }
        return result.toString();
    }

    /**
     * 读取数据流
     *
     * @param stream
     * @param result
     * @return
     * @throws IOException
     */
    private static BufferedReader readStream(InputStream stream, StringBuilder result) throws IOException {
        // 定义BufferedReader输入流来读取URL的响应,设置编码方式
        BufferedReader in = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
        String line;
        // 读取返回的内容
        while ((line = in.readLine()) != null) {
            result.append(line);
        }
        return in;
    }

    /**
     * 下载文件
     *
     * @param serverFileName 下载的服务器文件路径
     * @param localFileName  保存的文件路径
     * @throws IOException
     */
    public static void downToLocal(String serverFileName, String localFileName) throws IOException {
        downToLocal(serverFileName, localFileName, null);
    }

    /**
     * 下载文件
     *
     * @param serverFileName 下载的服务器文件路径
     * @param localFileName  保存的文件路径
     * @param runProcess     进度处理
     * @throws IOException
     */
    public static void downToLocal(String serverFileName, String localFileName, RunProcess runProcess) throws IOException {
        int byteRead;
        URL url = new URL(serverFileName);
        URLConnection conn = url.openConnection();
        conn.setConnectTimeout(HTTP_CONNNECT_TIMEOUT);
        conn.setReadTimeout(HTTP_READ_TIMEOUT);
        InputStream inStream = conn.getInputStream();
        try {
            ProcessData data = new ProcessData(serverFileName, conn.getContentLengthLong());
            FileOutputStream outputStream = new FileOutputStream(localFileName);
            try {
                byte[] buffer = new byte[1204];
                while ((byteRead = inStream.read(buffer)) != -1) {
                    data.processAdd(runProcess, byteRead);
                    outputStream.write(buffer, 0, byteRead);
                }
            } finally {
                outputStream.close();
            }
        } finally {
            inStream.close();
        }
    }


}