使用GET或POST请求与外部系统交互

@Slf4j
public class HttpClientUtil {
//path为外部系统的URL,body为JSON类型的参数
    public static String doPost(String path, String body) throws BusinessException {
        return doPost(path, body, null);
    }

    public static String doPost(String path, String body, String domainKey)throws BusinessException {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        HttpURLConnection conn = null;
        try {
            URL url = new URL(path);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            //发送 POST 请求必须设置为 true
            conn.setDoOutput(true);
            conn.setDoInput(true);

            //设置连接超时时间和读取超时时间
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            conn.setRequestProperty("Accept", "application/json");
            if(domainKey != null){
                conn.setRequestProperty("Domain-Key", domainKey);
            }
            //获取输出流
            out = new OutputStreamWriter(conn.getOutputStream(),"UTF-8");
            String jsonStr = body;
//            String encoding = out.getEncoding();
            out.write(jsonStr);
            out.flush();
            out.close();
            //取得输入流,并使用 Reader 读取
            if (200 == conn.getResponseCode()) {
                in = new BufferedReader(new InputStreamReader(conn.getInputStream(),
                        "UTF-8"));
                String line;
                while ((line = in.readLine()) != null) {
                    result.append(line);
                    log.info(line);
                }
            } else {
                log.info("ResponseCode is an error code:" + conn.getResponseCode());
                throw new BusinessException("调用接口时返回编码异常:" + conn.getResponseCode());
            }
        } catch (IOException e) {
            log.error("接口调用超时");
            throw new BusinessException("接口调用异常:"+e.getMessage());
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ioe) {
               log.debug(ioe.getMessage());
            }
        }
        return result.toString();
    }

    public static String doGet(String path, Map<String, Object> params) {
        HttpURLConnection conn = null;
        InputStream is = null;
        StringBuilder pathStr = new StringBuilder(path);
        BufferedReader br = null;
        StringBuilder result = new StringBuilder();
        try {
            if (params != null) {
                StringBuilder paramStr = new StringBuilder();
                for (Map.Entry key : params.entrySet()) {
                    if (paramStr.length()!=0) {
                        paramStr.append('&');
                    }
                    paramStr.append(key.getKey());
                    paramStr.append("=");
                    paramStr.append(key.getValue());
//                    paramStr += key + '=' + params.get(key).toString();
                }
                if (path.indexOf('?') > 0) {
                    pathStr.append("&" + paramStr) ;
                } else {
                    pathStr.append("?" + paramStr);
                }
            }
            //创建远程 url 连接对象
            URL url = new URL(pathStr.toString());
            //通过远程 url 连接对象打开一个连接,强转成 HTTPURLConnection 类
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            //设置连接超时时间和读取超时时间
            conn.setConnectTimeout(120000);
            conn.setReadTimeout(120000);
            conn.setRequestProperty("Accept", "application/json");
            //发送请求
            conn.connect();
            //通过 conn 取得输入流,并使用 Reader 读取
            if (200 == conn.getResponseCode()) {
                is = conn.getInputStream();
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                String line;
                while ((line = br.readLine()) != null) {
                    result.append(line);
                    log.info(line);
                }
            } else {
                log.info("ResponseCode is an error code:" + conn.getResponseCode());
            }
        } catch (IOException e) {
           log.debug(e.getMessage());
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
                if (is != null) {
                    is.close();
                }
            } catch (IOException ioe) {
               log.debug(ioe.getMessage());
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return result.toString();
    }

    public static String doGetAndHeard(String path,String cookie,Map<String, Object> params) {
        HttpURLConnection conn = null;
        InputStream is = null;
        StringBuilder pathStr = new StringBuilder(path);

        BufferedReader br = null;
        StringBuilder result = new StringBuilder();
        try {
            if (params != null) {
                StringBuilder paramStr = new StringBuilder(path);
                for (Map.Entry key : params.entrySet()) {
                    if (paramStr.length()!=0) {
                        paramStr.append("&") ;
                    }
                    paramStr.append(key.getKey());
                    paramStr.append("=");
                    paramStr.append(key.getValue());
                }
                if (path.indexOf('?') > 0) {
                    pathStr.append("&"+ paramStr);
                } else {
                    pathStr.append("?"+paramStr);
                }
            }
            //创建远程 url 连接对象
            URL url = new URL(pathStr.toString());
            //通过远程 url 连接对象打开一个连接,强转成 HTTPURLConnection 类
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            //设置连接超时时间和读取超时时间
            conn.setConnectTimeout(120000);
            conn.setReadTimeout(120000);
            conn.setRequestProperty("Accept", "application/json");
            conn.setRequestProperty("Cookie", cookie);
            //发送请求
            conn.connect();
            //通过 conn 取得输入流,并使用 Reader 读取
            if (200 == conn.getResponseCode()) {
                is = conn.getInputStream();
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                String line;
                while ((line = br.readLine()) != null) {
                    result.append(line);
                    log.info(line);
                }
            } else {
                log.info("ResponseCode is an error code:" + conn.getResponseCode());
            }
        } catch (IOException e) {
            log.debug(e.getMessage());

        } finally {
            try {
                if (br != null) {
                    br.close();
                }
                if (is != null) {
                    is.close();
                }
            } catch (IOException ioe) {
                log.debug(ioe.getMessage());
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return result.toString();
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值