HttpClient request payload post请求(传输的数据为json)

来源:互联网 发布:登陆淘宝网 编辑:程序博客网 时间:2024/06/13 21:14
private static String postJsonFile1(String url, Map params, Map<String, String> headers, int connectTimeout, int readTimeout, String encoding, HttpUtil.HttpMethod method) {        JSONObject jsonObject = JSONObject.fromObject(params);        URL uUrl = null;        HttpURLConnection conn = null;        BufferedWriter out = null;        BufferedReader in = null;        try {            //创建和初始化连接            uUrl = new URL(url);            conn = (HttpURLConnection) uUrl.openConnection();            conn.setRequestProperty("content-type", "application/json");            conn.setRequestMethod(method.toString());            conn.setDoOutput(true);            conn.setDoInput(true);            //设置连接超时时间            conn.setConnectTimeout(connectTimeout);            //设置读取超时时间            conn.setReadTimeout(readTimeout);            //指定请求header参数            if (headers != null && headers.size() > 0) {                Set<String> headerSet = headers.keySet();                for (String key : headerSet) {                    conn.setRequestProperty(key, headers.get(key));                }            }            out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), encoding));            out.write(jsonObject.toString());            out.flush();            //接收返回结果            StringBuilder result = new StringBuilder();            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), encoding));            if (in != null) {                String line = "";                while ((line = in.readLine()) != null) {                    result.append(line);                }            }            return result.toString();        } catch (Exception e) {            logger.error("调用接口[" + url + "]失败!请求URL:" + url + ",参数:" + jsonObject, e);            System.out.println("发送POST请求出现异常!" + e);            //处理错误流,提高http连接被重用的几率            try {                byte[] buf = new byte[100];                InputStream es = conn.getErrorStream();                if (es != null) {                    while (es.read(buf) > 0) {                        ;                    }                    es.close();                }            } catch (Exception e1) {                e1.printStackTrace();            }        } finally {            try {                if (out != null) {                    out.close();                }            } catch (Exception e) {                e.printStackTrace();            }            try {                if (in != null) {                    in.close();                }            } catch (Exception e) {                e.printStackTrace();            }            //关闭连接            if (conn != null) {                conn.disconnect();            }        }        return null;    }
阅读全文
0 0
原创粉丝点击