httpclient POST请求 org.apache.commons.httpclient.methods.PostMethod

本文介绍了一种使用Java的HttpClient库发送POST请求的方法。通过构造HttpClient实例并创建POST方法,文章展示了如何设置请求头、填充表单参数,并处理响应状态码。在成功发送请求并获得200状态码的情况下,返回了成功的标志。

public Map<String, Object> sendHttpClient(String url,Map<String, Object> map){
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("success", true);
         // 构造HttpClient的实例
        HttpClient httpClient = new HttpClient();
        // 创建POST方法的实例
//        url="http://localhost:8080/*********.action";
        PostMethod method = new PostMethod(url);

        // 这个basicNameValue**放在List中
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        // 创建basicNameValue***对象参数
        if (map != null) {
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                nameValuePairs.add(new NameValuePair(entry.getKey(), entry.getValue().toString()));
            }
        }
        // 填入各个表单域的值
        NameValuePair[] param = nameValuePairs.toArray(new NameValuePair[nameValuePairs.size()]);
        method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

        // 将表单的值放入postMethod中
        method.addParameters(param);
        try {
            // 执行postMethod
            int statusCode = httpClient.executeMethod(method);
            logger.debug("################# sendHttpClient state "+statusCode);
            if (method.getStatusCode() == HttpStatus.SC_OK) {
                logger.debug(method.getResponseBodyAsStream());
                return result;
//                return StreamUtils.copyToString(method.getResponseBodyAsStream(), Charset.forName("utf-8"));
            }
        } catch (UnsupportedEncodingException e1) {
            logger.error(e1.getMessage());
            throw new RuntimeException(e1.getMessage());
        } catch (IOException e) {
            logger.error("执行HTTP Post请求" + url + "时,发生异常!" + e.toString());
            throw new RuntimeException(e.getMessage());
        } finally {
            method.releaseConnection();
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值