[心缘地方]同学录
首页 | 功能说明 | 站长通知 | 最近更新 | 编码查看转换 | 代码下载 | 常见问题及讨论 | 《深入解析ASP核心技术》 | 王小鸭自动发工资条VBA版
登录系统:用户名: 密码: 如果要讨论问题,请先注册。

[整理]Httpclient 4.5 get和post的工具类

上一篇:[备忘]mybatis报错,attempted to return null from a method with a primitive return type (int)
下一篇:[备忘]PHP里奇怪的语法:foreach($arr as $k=>$v) 请问里面的“=>”符号是什么意思

添加日期:2015/9/10 18:18:18 快速返回   返回列表 阅读3372次
使用的是httpcore-4.4.4.jar和httpclient-4.5.1.jar
到Maven库下载即可。
http://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient/4.5.1
http://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore/4.4.4


package cn.xxx.util;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * HTTP请求工具类.
 * 
 */
public class HttpUtil {

    /**
     * Get方式取得URL的内容.
     * 
     * @param url
     *            访问的网址
     * @return
     */
    public static String getUrlContent(String url) {

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;
        try {

            // 执行请求
            response = httpclient.execute(httpGet);

            // 转换结果
            HttpEntity entity1 = response.getEntity();
            String html = EntityUtils.toString(entity1);

            // 消费掉内容
            EntityUtils.consume(entity1);
            return html;
        } catch (IOException e) {

            return "";
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
            }
        }
    }

    /**
     * Post方式取得URL的内容,默认为"application/x-www-form-urlencoded"格式,charset为UTF-8.
     * 
     * @param url
     *            访问的网址
     * @param content
     *            提交的数据
     * @return
     */
    public static String postToUrl(String url, String content) {
        return postToUrl(url, content, "application/x-www-form-urlencoded",
                "UTF-8");
    }

    /**
     * json字符串形式请求
     * 
     * @param url
     * @param content
     * @return
     */
    public static String postForJson(String url, String content) {
        return postToUrl(url, content, "application/json", "UTF-8");
    }

    /**
     * Post方式取得URL的内容.
     * 
     * @param url
     *            访问的网址
     * @param content
     *            提交的数据
     * @param contentType
     *            数据类型
     * @param charset
     *            字符集
     * @return
     */
    public static String postToUrl(String url, String content,
            String contentType, String charset) {
        return postToUrl(url, content, contentType, charset, null);
    }

    /**
     * Post方式取得URL的内容.
     * 
     * @param url
     *            访问的网址
     * @param content
     *            提交的数据
     * @param contentType
     *            数据类型
     * @param charset
     *            字符集
     * @param headerMap
     *            要增加的header信息
     * @return
     */
    public static String postToUrl(String url, String content,
            String contentType, String charset, Map<String, String> headerMap) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);

        // 设置内容
        ContentType type = ContentType.create(contentType,
                Charset.forName(charset));
        StringEntity reqEntity = new StringEntity(content, type);
        httpPost.setEntity(reqEntity);

        // Header
        if (headerMap != null && headerMap.size() > 0) {
            for (String key : headerMap.keySet()) {
                httpPost.addHeader(key, headerMap.get(key));
            }
        }

        // 这是超时
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(30000).setConnectTimeout(60000).build();// 设置请求和传输超时时间
        httpPost.setConfig(requestConfig);

        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpclient.execute(httpPost);

            // 转换结果
            HttpEntity entity1 = response.getEntity();
            String html = EntityUtils.toString(entity1, charset);

            // 消费掉内容
            EntityUtils.consume(entity1);
            return html;
        } catch (IOException ex) {
            return "";
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
            }
        }
    }

    public static void main(String[] args) {

        String html = postForJson("http://xxx.com/",
                "{\"frm\":\"frm\",\"ipcc\":\"ipcc\"}");
        System.out.println(html);

    }
}

 

评论 COMMENTS
没有评论 No Comments.

添加评论 Add new comment.
昵称 Name:
评论内容 Comment:
验证码(不区分大小写)
Validation Code:
(not case sensitive)
看不清?点这里换一张!(Change it here!)
 
评论由管理员查看后才能显示。the comment will be showed after it is checked by admin.
CopyRight © 心缘地方 2005-2999. All Rights Reserved