java post请求

该代码片段展示了如何使用HttpClient库进行POST请求,处理HTTP头和请求参数。它支持发送JSON和表单数据,并处理HTTPS连接。在请求中设置超时、字符集,并根据需要添加自定义头部。如果响应状态码为200,则读取并返回响应内容。
摘要由CSDN通过智能技术生成
public static String doPostWithHeader(String url, List<Header> headerList, Map<String, Object> params, boolean isFormData) throws Exception {
        logger.debug("Post Url:" + url + ",Params:" + params);
        StringBuffer result = new StringBuffer();
        HttpClient client = new HttpClient();
        client.getParams().setIntParameter("http.connection.timeout", 10000);
        if (url.startsWith("https")) {
            Protocol myhttps = new Protocol("https", new HttpSSLProtocolSocketHandler(), 443);
            Protocol.registerProtocol("https", myhttps);
        }

        PostMethod method = new PostMethod(url);
        method.getParams().setParameter("http.protocol.content-charset", "UTF-8");
        method.addRequestHeader(new Header("Content-Type", isFormData ? "application/x-www-form-urlencoded" : "application/json"));
        Header str;
        if (headerList != null && headerList.size() > 0) {
            Iterator var7 = headerList.iterator();

            while(var7.hasNext()) {
                str = (Header)var7.next();
                method.addRequestHeader(str);
            }
        }

        if (isFormData) {
            if (!ObjectUtils.isEmpty(params)) {
                NameValuePair[] data = new NameValuePair[params.size()];
                int i = 0;

                Map.Entry entry;
                for(Iterator i$ = params.entrySet().iterator(); i$.hasNext(); data[i++] = new NameValuePair((String)entry.getKey(), (String)entry.getValue())) {
                    entry = (Map.Entry)i$.next();
                }

                method.setRequestBody(data);
            }
        } else if (params != null) {
            String requestJson = JSONObject.toJSONString(params);
            method.setRequestBody(requestJson);
        }

        try {
            client.executeMethod(method);
            if (method.getStatusCode() == 200) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), StandardCharsets.UTF_8));
                str = null;

                String str;
                while((str = reader.readLine()) != null) {
                    result.append(str);
                }
            }
        } finally {
            method.releaseConnection();
        }

        logger.debug("Post Return:" + result.toString());
        return result.toString();
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值