package com.j1.weixin.util;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.log4j.Logger;

public class HttpUtils {
    /**
     * 发送HTTP请求
     *
     * @param url
     * @param propsMap 发送的参数
     */
    public static HttpResponse httpPost(String url, Map<String, Object> propsMap) {
        HttpResponse response = new HttpResponse();
        String responseMsg = "";

        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);// POST请求
        if (propsMap != null) {
            // 参数设置
            Set<String> keySet = propsMap.keySet();
            NameValuePair[] postData = new NameValuePair[keySet.size()];
            int index = 0;
            for (String key : keySet) {
                postData[index++] = new NameValuePair(key, propsMap.get(key)
                        .toString());
            }
            postMethod.addParameters(postData);
        }
        postMethod.getParams().setParameter(
                HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
        postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        try {
            int statusCode = httpClient.executeMethod(postMethod);// 发送请求
            response.setStatusCode(statusCode);
            if (statusCode == HttpStatus.SC_OK) {
                // 读取内容
                byte[] responseBody = postMethod.getResponseBody();
                // 处理返回的内容
                responseMsg = new String(responseBody, "utf-8");
            }
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            postMethod.releaseConnection();// 关闭连接
        }
        response.setContent(responseMsg);
        return response;
    }

    /**
     * 发送HTTP请求
     *
     * @param url
     */
    public static HttpResponse httpGet(String url) {
        HttpResponse response = new HttpResponse();
        String responseMsg = "";

        HttpClient httpClient = new HttpClient();
        GetMethod getMethod = new GetMethod(url);

        try {
            int statusCode = httpClient.executeMethod(getMethod);// 发送请求
            response.setStatusCode(statusCode);
            if (statusCode == HttpStatus.SC_OK) {
                // 读取内容
                byte[] responseBody = getMethod.getResponseBody();
                // 处理返回的内容
                responseMsg = new String(responseBody, "utf-8");
            }
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            getMethod.releaseConnection();// 关闭连接
        }
        response.setContent(responseMsg);
        return response;
    }

    /**
     * 发送HTTP--GET请求
     *
     * @param url
     * @param propsMap
     *            发送的参数
     */
    public static String httpGetSend(String url) {
        String responseMsg = "";
        HttpClient httpClient = new HttpClient();
        GetMethod getMethod = new GetMethod(url);// GET请求
        try {
            // http超时5秒
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
            // 设置 get 请求超时为 5 秒
            getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
            getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
            httpClient.executeMethod(getMethod);// 发送请求
            // 读取内容
            byte[] responseBody = getMethod.getResponseBody();
            // 处理返回的内容
            responseMsg = new String(responseBody, "utf-8");
        } catch (Exception e) {
            Logger.getLogger(HttpUtils.class).error(e.getMessage());
            e.printStackTrace();
        } finally {
            getMethod.releaseConnection();// 关闭连接
        }
        return responseMsg;
    }

    /**
     * 发送HTTP请求
     *
     * @param url
     * @param propsMap
     *            发送的参数
     */
    public static String httpSend(String url, Map<String, Object> propsMap) {
        String responseMsg = "";

        HttpClient httpClient = new HttpClient();

        PostMethod postMethod = new PostMethod(url);// POST请求

//        postMethod.
        // 参数设置
        Set<String> keySet = propsMap.keySet();
        NameValuePair[] postData = new NameValuePair[keySet.size()];
        int index = 0;
        for (String key : keySet) {
            postData[index++] = new NameValuePair(key, propsMap.get(key)
                    .toString());
        }
        postMethod.addParameters(postData);
        try {
            httpClient.executeMethod(postMethod);// 发送请求
//            Log.info(postMethod.getStatusCode());
            // 读取内容
            byte[] responseBody = postMethod.getResponseBody();
            // 处理返回的内容
            responseMsg = new String(responseBody);

        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            postMethod.releaseConnection();// 关闭连接
        }
        return responseMsg;
    }

    /**
     * 发送Post HTTP请求
     *
     * @param url
     * @param propsMap
     *            发送的参数
     * @throws IOException
     * @throws HttpException
     */
    public static PostMethod httpSendPost(String url, Map<String, Object> propsMap,String authrition) throws Exception {
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);// POST请求
        postMethod.addRequestHeader("Authorization",authrition);
        postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8");
        // 参数设置
        Set<String> keySet = propsMap.keySet();
        NameValuePair[] postData = new NameValuePair[keySet.size()];
        int index = 0;
        for (String key : keySet) {
            postData[index++] = new NameValuePair(key, propsMap.get(key)
                    .toString());
        }
        postMethod.addParameters(postData);

        httpClient.executeMethod(postMethod);// 发送请求
        return postMethod;
    }

    /**
     * 发送Post HTTP请求
     *
     * @param url
     * @param propsMap
     *            发送的参数
     * @throws IOException
     * @throws HttpException
     */
    public static PostMethod httpSendPost(String url, Map<String, Object> propsMap) throws Exception {
        String responseMsg = "";
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);// POST请求
        postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8");
        // 参数设置
        Set<String> keySet = propsMap.keySet();
        NameValuePair[] postData = new NameValuePair[keySet.size()];
        int index = 0;
        for (String key : keySet) {
            postData[index++] = new NameValuePair(key, propsMap.get(key)
                    .toString());
        }
        postMethod.addParameters(postData);

        httpClient.executeMethod(postMethod);// 发送请求
        return postMethod;
    }

    /**
     * 发送Get HTTP请求
     *
     * @param url
     * @param propsMap
     *            发送的参数
     * @throws IOException
     * @throws HttpException
     */
    public static GetMethod httpSendGet(String url, Map<String, Object> propsMap) throws Exception {
        String responseMsg = "";
        HttpClient httpClient = new HttpClient();
        GetMethod getMethod = new GetMethod(url);// GET请求
        getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8");
        // 参数设置
        Set<String> keySet = propsMap.keySet();
        NameValuePair[] postData = new NameValuePair[keySet.size()];
        int index = 0;
        for (String key : keySet) {
            getMethod.getParams().setParameter(key, propsMap.get(key)
                    .toString());
        }

        httpClient.executeMethod(getMethod);// 发送请求
        return getMethod;
    }

}

post 封装Map 发送请求的更多相关文章

  1. Python 使用 requests 模块发送请求的使用及封装

    一.requests 模块基本使用 1.准备接口的URL.请求参数.请求头 # 1. 构造注册.登录.充值请求的url register_url = "注册url" login_u ...

  2. Java爬虫(一)利用GET和POST发送请求,获取服务器返回信息

    本人所使用软件 eclipse fiddle UC浏览器 分析请求信息 以知乎(https://www.zhihu.com)为例,模拟登陆请求,获取登陆后首页,首先就是分析请求信息. 用UC浏览器F1 ...

  3. http post发送请求

    一: 用java自带URL发送 public synchronized JSONObject getJSON(String url2, String param) { try { URL url = ...

  4. consumer发送请求,接收响应

    一般情况,consumer发送请求时,创建一个DefaultFuture对象,然后阻塞并等待响应.DefaultFuture类,封装了请求和响应: // 省略其他代码 public class Def ...

  5. 九、封装登录POST请求、登录后POST请求以及GET请求

    一.封装登录后POST请求以及GET请求 /** * 全局运行时环境参数管理器 */ public static Map<String, String> BASE_GLOBAL_MAP; ...

  6. RestTemplate发送请求并携带header信息

    1.使用restTemplate的postForObject方法 注:目前没有发现发送携带header信息的getForObject方法. HttpHeaders headers = new Http ...

  7. 封装的ajax请求

    在做登录注册这类提交表单数据时,我们经常需要局部刷新网页来验证用户输入的信息,这就需要用到ajax请求,我们通常需要获取表单中的数据,发起ajax请求,通过服务程序,与数据库的数据进行比对,判断信息的 ...

  8. ajax-向服务器发送请求

    ajax-向服务器发送请求 1.将请求发送到服务器,使用XMLHttpRequest对象的 open() 和 send() 方法.     xmlhttp. open(method,url,async ...

  9. Android 网络请求库volley的封装,让请求更方便

    首先封装一下volley 请求 public class CustomRequest extends StringRequest { private static final String TAG = ...

随机推荐

  1. 分享29个超赞的响应式Web设计

    原文自:http://www.csdn.net/article/2013-01-16/2813678-responsive-design-websites 最近几年,响应式Web设计不断印入人们眼帘, ...

  2. 关于html5

    html5   是用来  将 js  和 css  结合起来 从而实现 各种功能 javascript 用来定义 html5   页面的逻辑 css 来定义 html5 中的显示样式

  3. JQuery重要知识点

    jQuery基本选择器----包括ID选择器,标签选择器,类选择器,通配选择器和组选择器5种 a. ID选择器: $("#id") b. 标签选择器:$("element ...

  4. Ajax 的同步与异步

    1.Ajax的工作原理如图: 2.同步 XMLHttpRequest 对象用于和服务器交换数据. XMLHttpRequest 对象如果要用于 AJAX 的话,其 open() 方法的 async 参 ...

  5. WPAD 的原理及实现

    WPAD 通过让浏览器自动发现代理服务器,使代理服务器对用户来说是透明的,进而轻松访问互联网.WPAD 可以借助 DNS 服务器或 DHCP 服务器来查询代理自动配置(PAC)文件的位置. 引言 代理 ...

  6. IOS中用模型取代字典的好处

    使用字典的坏处 一般情况下,设置数据和取出数据都是用“字符串类型的key”,编写这些key时,编译器不会有任何友情提示,需要手敲 dict[@“name”]=@“Kevin”; NSString *n ...

  7. AT24C512与AT24C512B的区别

    前几日公司采购人员说现在AT24C512要停产了,替代型号为AT24C512B,因为公司产品中使用该器件较多,因此专门又研究了一下这两个芯片,发现还是有很多地方不同的. (1)AT24C512输入电压 ...

  8. WebService引擎Axis2完美教程

    1.http://wenku.baidu.com/link?url=O05r69TGaLmrJrjJqGz-5EASox8FhhUO6i97xoUOV2dcbh8BEnOlX2EN3nuYGE_3HE ...

  9. 日志式文件系统:SGI的xfs, Reiserfs, IBM的jfs, ext3fs

    日志文件(Log files)是包含系统消息的文件,包括内核.服务.在系统上运行的应用程序等.不同的日志文件记载不同的信息.日志文件系统比传统的文件系统安全,因为它用独立的日志文件跟踪磁盘内容的变化. ...

  10. 后缀数组:SPOJ SUBST1 - New Distinct Substrings

    Given a string, we need to find the total number of its distinct substrings. Input T- number of test ...