HttpUtils.java 4.31 KB
package com.bsth.utils;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author hill
 * @date
 */
public class HttpUtils {

    private final static Logger log = LoggerFactory.getLogger(HttpUtils.class);

    public static void request(String url) {
        request(url, new CallBack() {
            @Override
            public void success(byte[] bytes, Map<String, List<String>> header) {
            	
            }

            @Override
            public void failed() {
            	
            }
        });
    }

    public static void request(String url, CallBack cb) {
        request(url, cb, "GET");
    }

    public static void request(String url, CallBack cb, String method) {
        request(url, cb, method, new HashMap<>());
    }

    public static void request(String url, CallBack cb, String method, Map<String, String> header) {
        request(url, cb, method, header, new HashMap<>());
    }

    public static void request(String url, CallBack cb, String method, Map<String, String> header, Map<String, Object> param) {
        InputStream in = null;
        OutputStream out = null;
        DataOutputStream printout = null;
        HttpURLConnection con = null;
        long start = System.currentTimeMillis();
        try {
            con = (HttpURLConnection)new URL(url).openConnection();
            con.setRequestMethod(method);
            con.setRequestProperty("keep-alive", "true");
            con.setRequestProperty("accept", "application/json");
            con.setRequestProperty("content-type", "application/json");
//            con.setRequestProperty("charset", "utf-8");
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setReadTimeout(180000);
            con.setConnectTimeout(180000);

            if (header.size() > 0) {
                for (Map.Entry<String, String> entry : header.entrySet()) {
                    con.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }

            if (param.size() > 0) {
                out = con.getOutputStream();
                StringBuilder sb = new StringBuilder();
                for (Map.Entry<String, Object> entry : param.entrySet()) {
                    sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
                }
                out.write(sb.substring(1).getBytes("UTF-8"));
                out.flush();
                
//                printout = new DataOutputStream(con.getOutputStream());
////				String jsonString = JSON.toJSONString(param);
////              printout.write(jsonString.getBytes("GBK"));
//                printout.write(("list="+param.get("list").toString()).getBytes("GBK"));
//                printout.flush();
            }

            in = con.getInputStream();
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            IOUtils.copy(in, bout); bout.close();
            if (con.getResponseCode() == 200) {
                cb.success(bout.toByteArray(), con.getHeaderFields());
            } else {
                log.info(new String(bout.toByteArray()));
                cb.failed();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            log.error("cost:" + (System.currentTimeMillis() - start));
            log.error("HttpUtils.request异常", e);
            cb.failed();
        } catch (Exception e) {
            log.error("处理异常", e);
        } finally {
            con.disconnect();
            try {
                if (in != null) in.close();
                if (printout != null) printout.close();
                if (out != null) out.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}