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


yanzg's avatar
yanzg committed
4
import com.yanzuoguang.util.exception.HttpCodeException;
yanzg's avatar
yanzg committed
5 6
import com.yanzuoguang.util.thread.ProcessData;
import com.yanzuoguang.util.thread.RunProcess;
yanzg's avatar
yanzg committed
7
import com.yanzuoguang.util.vo.MapRow;
yanzg's avatar
yanzg committed
8

yanzg's avatar
yanzg committed
9
import java.io.*;
yanzg's avatar
yanzg committed
10
import java.net.HttpURLConnection;
yanzg's avatar
yanzg committed
11 12
import java.net.URL;
import java.net.URLConnection;
yanzg's avatar
yanzg committed
13
import java.util.Map;
yanzg's avatar
yanzg committed
14 15 16

/**
 * HTTP请求工具类
17
 *
yanzg's avatar
yanzg committed
18
 * @author 颜佐光
yanzg's avatar
yanzg committed
19 20 21
 */
public class HttpHelper {

yanzg's avatar
yanzg committed
22 23 24
    /**
     * 链接超时
     */
yanzg's avatar
yanzg committed
25
    public static int HTTP_CONNECT_TIMEOUT = 3 * 1000;
yanzg's avatar
yanzg committed
26 27 28
    /**
     * 读取超时
     */
yanzg's avatar
yanzg committed
29
    public static int HTTP_READ_TIMEOUT = 12 * 1000;
yanzg's avatar
yanzg committed
30 31 32 33
    /**
     * 字符编码
     */
    public static final String CHARSET_DEFAULT = "UTF-8";
yanzg's avatar
yanzg committed
34

yanzg's avatar
yanzg committed
35 36 37 38 39 40 41 42 43 44 45 46 47 48
    /**
     * 获取请求参数
     *
     * @param obj 对象
     * @return
     */
    public static String getUrlParameter(Object obj) {
        return getUrlParameter(obj, "UTF-8");
    }

    /**
     * 获取请求参数
     *
     * @param obj 对象
yanzg's avatar
yanzg committed
49
     * @return 请求参数字符串
yanzg's avatar
yanzg committed
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
     */
    public static String getUrlParameter(Object obj, String charset) {
        MapRow to = JsonHelper.to(obj, MapRow.class);
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Object> kvp : to.entrySet()) {
            if (sb.length() > 0) {
                sb.append("&");
            }
            sb.append(UrlHelper.encoding(kvp.getKey(), charset));
            sb.append("=");
            sb.append(UrlHelper.encoding(StringHelper.toString(kvp.getValue()), charset));
        }
        return sb.toString();
    }

    /**
     * 获取连接
     *
     * @param url 请求地址
yanzg's avatar
yanzg committed
69 70
     * @return 链接
     * @throws IOException 抛出的异常信息
yanzg's avatar
yanzg committed
71 72 73 74 75 76 77 78 79 80
     */
    public static HttpURLConnection getConn(String url) throws IOException {
        return getConn(url, null, false);
    }

    /**
     * 获取连接
     *
     * @param url    请求地址
     * @param header 请求头
yanzg's avatar
yanzg committed
81 82
     * @return 链接
     * @throws IOException 抛出的异常信息
yanzg's avatar
yanzg committed
83 84 85 86 87 88 89 90 91 92
     */
    public static HttpURLConnection getConn(String url, Map<String, String> header) throws IOException {
        return getConn(url, header, false);
    }

    /**
     * 获取连接
     *
     * @param url               请求地址
     * @param isApplicationJson 是否请求json
yanzg's avatar
yanzg committed
93 94
     * @return 链接
     * @throws IOException 抛出的异常信息
yanzg's avatar
yanzg committed
95 96 97 98 99 100 101 102 103 104 105
     */
    public static HttpURLConnection getConn(String url, boolean isApplicationJson) throws IOException {
        return getConn(url, null, isApplicationJson);
    }

    /**
     * 获取连接
     *
     * @param url               请求地址
     * @param header            请求头
     * @param isApplicationJson 是否请求json
yanzg's avatar
yanzg committed
106 107
     * @return 链接
     * @throws IOException 抛出的异常信息
yanzg's avatar
yanzg committed
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
     */
    public static HttpURLConnection getConn(String url, Map<String, String> header, boolean isApplicationJson) 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)");
        if (isApplicationJson) {
            httpConn.setRequestProperty("Content-Type", "application/json");
        }
        // 处理自定义头
        if (header != null) {
            for (Map.Entry<String, String> item : header.entrySet()) {
                httpConn.setRequestProperty(item.getKey(), item.getValue());
            }
        }
        // 设置POST方式
        httpConn.setDoInput(true);
        httpConn.setDoOutput(true);
        httpConn.setConnectTimeout(HTTP_CONNECT_TIMEOUT);
        httpConn.setReadTimeout(HTTP_READ_TIMEOUT);
        return httpConn;
    }

yanzg's avatar
yanzg committed
135 136 137 138 139 140 141 142 143 144 145
    /**
     * 发送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
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
            return post(httpConn, jsonString, CHARSET_DEFAULT);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * 发送POST请求,当请求失败时,抛出异常或返回空字符串
     *
     * @param url 目的地址
     * @return 远程响应结果
     */
    public static String get(String url) {
        return get(url, "UTF-8");
    }

    /**
     * 发送POST请求,当请求失败时,抛出异常或返回空字符串
     *
     * @param url 目的地址
     * @return 远程响应结果
     */
    public static String get(String url, String charset) {
        try {
            // 打开URL连接
            java.net.HttpURLConnection httpConn = getConn(url);
            httpConn.setRequestMethod("GET");
            return get(httpConn, charset);
yanzg's avatar
yanzg committed
174
        } catch (Exception ex) {
yanzg's avatar
yanzg committed
175
            throw new RuntimeException(ex);
yanzg's avatar
yanzg committed
176 177 178 179 180 181 182 183 184 185 186 187 188
        }
    }

    /**
     * 发送POST请求,当请求失败时,抛出异常或返回空字符串
     *
     * @param url        目的地址
     * @param jsonString 请求参数,json字符串。
     * @return 远程响应结果
     */
    public static String postApplicationJSON(String url, String jsonString) {
        try {
            // 打开URL连接
yanzg's avatar
yanzg committed
189
            java.net.HttpURLConnection httpConn = getConn(url, true);
yanzg's avatar
yanzg committed
190
            return post(httpConn, jsonString, "UTF-8");
yanzg's avatar
yanzg committed
191
        } catch (Exception ex) {
yanzg's avatar
yanzg committed
192
            throw new RuntimeException(ex);
yanzg's avatar
yanzg committed
193 194 195 196 197 198
        }
    }

    /**
     * 发送POST请求,当请求失败时,抛出异常或返回空字符串
     *
199
     * @param httpConn   链接信息
yanzg's avatar
yanzg committed
200 201 202
     * @param jsonString 请求参数,json字符串。
     * @return 远程响应结果
     */
yanzg's avatar
yanzg committed
203
    public static String post(HttpURLConnection httpConn, String jsonString) throws IOException {
yanzg's avatar
yanzg committed
204 205 206 207 208 209 210 211 212 213 214 215
        return post(httpConn, jsonString, CHARSET_DEFAULT);
    }

    /**
     * 发送POST请求,当请求失败时,抛出异常或返回空字符串
     *
     * @param httpConn   链接信息
     * @param jsonString 请求参数,json字符串。
     * @param charset    输出编码
     * @return 远程响应结果
     */
    public static String post(HttpURLConnection httpConn, String jsonString, String charset) throws IOException {
yanzg's avatar
yanzg committed
216
        // 返回的结果
yanzg's avatar
yanzg committed
217
        StringBuilder result = new StringBuilder();
yanzg's avatar
yanzg committed
218 219
        // 读取响应输入流
        BufferedReader in = null;
yanzg's avatar
yanzg committed
220
        PrintWriter out = null;
yanzg's avatar
yanzg committed
221
        // 处理请求参数
yanzg's avatar
yanzg committed
222 223 224 225 226 227 228 229 230
        String params = "";
        try {
            params = jsonString;
            // 获取HttpURLConnection对象对应的输出流
            out = new PrintWriter(httpConn.getOutputStream());
            // 发送请求参数
            out.write(params);
            // flush输出流的缓冲
            out.flush();
yanzg's avatar
yanzg committed
231

yanzg's avatar
yanzg committed
232 233 234 235 236 237 238 239
            int returnCode = httpConn.getResponseCode();
            if (returnCode == HttpURLConnection.HTTP_OK) {
                in = readStream(httpConn.getInputStream(), result, charset);
            } else {
                throw new HttpCodeException(StringHelper.toString(returnCode), httpConn.getResponseMessage());
            }
        } catch (HttpCodeException ex) {
            throw ex;
240
        } catch (Exception ex) {
yanzg's avatar
yanzg committed
241
            in = readStream(httpConn.getErrorStream(), result, charset);
yanzg's avatar
yanzg committed
242
            throw new HttpCodeException(StringHelper.toString(httpConn.getResponseCode()), ex.getMessage(), result.toString(), ex);
yanzg's avatar
yanzg committed
243 244 245 246 247 248 249 250
        } finally {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        }
yanzg's avatar
yanzg committed
251
        return result.toString();
yanzg's avatar
yanzg committed
252
    }
yanzg's avatar
yanzg committed
253

yanzg's avatar
yanzg committed
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
    /**
     * 发送GET请求,当请求失败时,抛出异常或返回空字符串
     *
     * @param httpConn 链接信息
     * @return 远程响应结果
     */
    public static String get(HttpURLConnection httpConn) throws IOException {
        return get(httpConn, CHARSET_DEFAULT);
    }

    /**
     * 发送GET请求,当请求失败时,抛出异常或返回空字符串
     *
     * @param httpConn 链接信息
     * @return 远程响应结果
     */
    public static String get(HttpURLConnection httpConn, String charset) throws IOException {
        // 返回的结果
        StringBuilder result = new StringBuilder();
        // 读取响应输入流
        BufferedReader in = null;
        try {
            // 获取HttpURLConnection对象对应的输出流
            in = readStream(httpConn.getInputStream(), result, charset);
        } catch (Exception ex) {
            in = readStream(httpConn.getErrorStream(), result, charset);
            throw new HttpCodeException(StringHelper.toString(httpConn.getResponseCode()), ex.getMessage(), result.toString(), ex);
        } finally {
            if (in != null) {
                in.close();
            }
        }
        return result.toString();
    }

289 290 291
    /**
     * 读取数据流
     *
yanzg's avatar
yanzg committed
292 293 294 295 296
     * @param stream  流
     * @param result  结果字符串
     * @param charset 编码方式
     * @return 读取的缓存流
     * @throws IOException IO异常
297
     */
yanzg's avatar
yanzg committed
298
    private static BufferedReader readStream(InputStream stream, StringBuilder result, String charset) throws IOException {
yanzg's avatar
yanzg committed
299 300 301
        if (stream == null) {
            return null;
        }
302
        // 定义BufferedReader输入流来读取URL的响应,设置编码方式
yanzg's avatar
yanzg committed
303
        BufferedReader in = new BufferedReader(new InputStreamReader(stream, charset));
304 305 306 307 308 309 310 311
        String line;
        // 读取返回的内容
        while ((line = in.readLine()) != null) {
            result.append(line);
        }
        return in;
    }

yanzg's avatar
yanzg committed
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
    /**
     * 下载文件
     *
     * @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();
yanzg's avatar
yanzg committed
335
        conn.setConnectTimeout(HTTP_CONNECT_TIMEOUT);
yanzg's avatar
yanzg committed
336
        conn.setReadTimeout(HTTP_READ_TIMEOUT);
yanzg's avatar
yanzg committed
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
        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
356
}