HttpHelper.java 5.15 KB
Newer Older
yanzg's avatar
yanzg committed
1 2 3
package com.yanzuoguang.util.helper;


yanzg's avatar
yanzg committed
4 5
import com.yanzuoguang.util.thread.ProcessData;
import com.yanzuoguang.util.thread.RunProcess;
yanzg's avatar
yanzg committed
6

yanzg's avatar
yanzg committed
7
import java.io.*;
yanzg's avatar
yanzg committed
8
import java.net.HttpURLConnection;
yanzg's avatar
yanzg committed
9 10
import java.net.URL;
import java.net.URLConnection;
yanzg's avatar
yanzg committed
11 12 13

/**
 * HTTP请求工具类
yanzg's avatar
yanzg committed
14
 * @author 颜佐光
yanzg's avatar
yanzg committed
15 16 17 18 19 20 21 22 23 24 25 26 27 28
 */
public class HttpHelper {

    /**
     * 发送POST请求,当请求失败时,抛出异常或返回空字符串
     *
     * @param url        目的地址
     * @param jsonString 请求参数,json字符串。
     * @return 远程响应结果
     */
    public static String post(String url, String jsonString) {
        try {
            // 打开URL连接
            java.net.HttpURLConnection httpConn = getConn(url);
yanzg's avatar
yanzg committed
29
            return post(httpConn, jsonString);
yanzg's avatar
yanzg committed
30
        } catch (Exception ex) {
yanzg's avatar
yanzg committed
31
            throw new RuntimeException(ex);
yanzg's avatar
yanzg committed
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
        }
    }

    /**
     * 发送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");
yanzg's avatar
yanzg committed
47
            return post(httpConn, jsonString);
yanzg's avatar
yanzg committed
48
        } catch (Exception ex) {
yanzg's avatar
yanzg committed
49
            throw new RuntimeException(ex);
yanzg's avatar
yanzg committed
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
        }
    }

    /**
     * 获取连接
     *
     * @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);
        return httpConn;
    }


    /**
     * 发送POST请求,当请求失败时,抛出异常或返回空字符串
     *
yanzg's avatar
yanzg committed
80
     * @param httpConn  链接信息
yanzg's avatar
yanzg committed
81 82 83
     * @param jsonString 请求参数,json字符串。
     * @return 远程响应结果
     */
yanzg's avatar
yanzg committed
84
    public static String post(HttpURLConnection httpConn, String jsonString) throws IOException {
yanzg's avatar
yanzg committed
85
        // 返回的结果
yanzg's avatar
yanzg committed
86
        StringBuilder result = new StringBuilder();
yanzg's avatar
yanzg committed
87 88
        // 读取响应输入流
        BufferedReader in = null;
yanzg's avatar
yanzg committed
89
        PrintWriter out = null;
yanzg's avatar
yanzg committed
90
        // 处理请求参数
yanzg's avatar
yanzg committed
91
        // StringBuffer sb = new StringBuffer();
yanzg's avatar
yanzg committed
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
        String params = "";
        try {
            params = jsonString;
            // 获取HttpURLConnection对象对应的输出流
            out = new PrintWriter(httpConn.getOutputStream());
            // 发送请求参数
            out.write(params);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应,设置编码方式
            in = new BufferedReader(new InputStreamReader(httpConn
                    .getInputStream(), "UTF-8"));
            String line;
            // 读取返回的内容
            while ((line = in.readLine()) != null) {
yanzg's avatar
yanzg committed
107
                result.append(line);
yanzg's avatar
yanzg committed
108 109 110 111 112 113 114 115 116
            }
        } finally {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        }
yanzg's avatar
yanzg committed
117
        return result.toString();
yanzg's avatar
yanzg committed
118
    }
yanzg's avatar
yanzg committed
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161

    /**
     * 下载文件
     *
     * @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();
        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();
        }
    }


yanzg's avatar
yanzg committed
162
}