`
annan211
  • 浏览: 446862 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论
收藏列表
标题 标签 来源
httpclient 【httpclient】httpclient发送表单POST请求
 public String formPost(String url, Map<String, String> params) throws IOException {
        if (url == null || url.trim().length() <= 0) {
            throw new IllegalArgumentException("POST url can not be empty");
        }
        Map<String, String> response = new HashMap<String, String>();
        PostMethod poster = new PostMethod(url);
        String content = "";
        String encoding = HTTP.UTF_8;
        String contentType = "application/x-www-form-urlencoded;charset=" + encoding;

        if (params != null && params.size() > 0) {
            content = format(params, encoding);
        }
        StringRequestEntity entity = new StringRequestEntity(content, contentType, encoding);
        poster.setRequestEntity(entity);
        httpClient.executeMethod(poster);
        return responseBodyAsString(poster);
    }

    private static String format(Map<String, String> parameters, final String encoding) {
        final StringBuilder sb = new StringBuilder();
        Set<Map.Entry<String, String>> entrySet = parameters.entrySet();
        Iterator<Map.Entry<String, String>> iterator = entrySet.iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            final String encodedName = encode(entry.getKey(), encoding);
            final String value = entry.getValue();
            final String encodedValue = value != null ? encode(value, encoding) : "";
            if (sb.length() > 0) {
                sb.append("&");
            }
            sb.append(encodedName);
            sb.append("=");
            sb.append(encodedValue);
        }
        return sb.toString();
    }

    public static String decode(final String content, final String encoding) {
        try {
            return URLDecoder.decode(content, encoding != null ? encoding : HTTP.DEFAULT_CONTENT_CHARSET);
        } catch (UnsupportedEncodingException problem) {
            throw new IllegalArgumentException(problem);
        }
    }

    public static String encode(final String content, final String encoding) {
        try {
            return URLEncoder.encode(content,  encoding != null ? encoding : HTTP.DEFAULT_CONTENT_CHARSET);
        } catch (UnsupportedEncodingException problem) {
            throw new IllegalArgumentException(problem);
        }
    }
Global site tag (gtag.js) - Google Analytics