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

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

        // 这个basicNameValue**放在List中
        List nameValuePairs = new ArrayList();
        // 创建basicNameValue***对象参数
        if (map != null) {
            for (Map.Entry 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();
        }
    }

你可能感兴趣的:(JAVA)