package com.founder.ec.common.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.Map;
import java.util.Set;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.httpclient.HttpException;

public class HttpSenderUtil {

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    public static  String httpSend(String url, Map<String, Object> propsMap)  throws Exception{
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);// POST请求
        String returnString ="";
        // 参数设置
        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);// 发送请求
            java.io.InputStream input = postMethod.getResponseBodyAsStream();
            returnString = convertStreamToString(input).toString();

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

    public static String convertStreamToString(java.io.InputStream input)
            throws Exception {
        BufferedReader reader = new BufferedReader(new InputStreamReader(input,
                "UTF-8"));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        input.close();
        return sb.toString();
    }

    public static void main(String[] strs){
        long time=new Date().getTime();
        String check=MD5.getMD5(time+"www.j1.com");
        String mobile="13053702096";
        String msg="尊敬的用户  , 您在健一网的安全验证码为897489,健一网祝您身体健康";
        String param="t="+time+"&mobile="+mobile+"&msg="+msg+"&check="+check;
        String res=HttpSenderUtil.sendPost("http://localhost:8080/ec-dec/page/sms/sendSms/code",param);
        System.out.println(res);
    }
    /**
     * 执行get方法
     * @param url
     * @param queryString
     * @return
     */
    public static String doGet(String url, String queryString) {
        String response = null;
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod(url);
        try {
                if (StringUtils.isNotBlank(queryString))
                        method.setQueryString(URIUtil.encodeQuery(queryString));
                client.executeMethod(method);
                if (method.getStatusCode() == HttpStatus.SC_OK) {
                        response = method.getResponseBodyAsString();
                }
        } catch (URIException e) {
            //logger.error("执行HTTP Get请求时,编码查询字符串“" + queryString + "”发生异常!", e);
        } catch (IOException e) {
            //logger.error("执行HTTP Get请求" + url + "时,发生异常!", e);
        } finally {
            method.releaseConnection();
        }
        return response;
    }

}

HttpSenderUtil向指定 URL 发送POST方法的请求的更多相关文章

  1. wemall doraemon中Android app商城系统向指定URL发送GET方法的请求代码

    URL的openConnection()方法将返回一个URLConnection对象,该对象表示应用程序和 URL 之间的通信链接.程序可以通过URLConnection实例向该URL发送请求.读取U ...

  2. 向指定URL发送GET方法获取资源,编码问题。 Rest风格

    http编码.今天遇到获取网页上的数据,用HTTP的GET请求访问url获取资源,网上有相应的方法.以前一直不知道什么事rest风格,现在我想就是开一个Controller,然后使人可以调用你的后台代 ...

  3. 向指定URL发送GET和POST请求

    package com.sinosoft.ap.wj.common.util; import java.io.BufferedReader;import java.io.IOException;imp ...

  4. 向指定URL发送GET、POST方法的请求

    /** * 向指定URL发送GET方法的请求 * * @param url * 发送请求的URL * @param param * 请求参数,请求参数应该是 name1=value1&name ...

  5. 向指定url发送Get/Post请求

    向指定url发送Get/Post请求 1.向指定url发送Get/Post请求 2.HttpUtil 工具类–向指定url发送Get/Post请求 1.向指定url发送Get/Post请求 impor ...

  6. java利用URL发送get和post请求

    import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import ...

  7. 向指定URL 发送POST请求的方法

    java发送psot请求: package com.tea.web.admin; import java.io.BufferedReader; import java.io.IOException; ...

  8. 获取域名,url,指定url参数的方法

    1.js获取域名的方法 1) var domain = document.domain 2) var domain = window.location.host 2.获取url的方法 1) var u ...

  9. 向指定url发送请求与获取响应

    string url = @"https://www.baidu.com"; //向指定服务器发起请求 HttpWebRequest request = (HttpWebReque ...

随机推荐

  1. 一道面试题 包含了new的细节 和运算符的优先级 还有属性访问机制

    function Foo() { getName = function () { alert(1); } return this; } Foo.getName = function () { aler ...

  2. java三大特性--多态(1)

    定义 对象具有多种形态 类型 引用的多态: 父类的引用指向自身对象 父类的引用指向子类对象 TrafficTool traffictool=new TrafficTool();//父类的引用指向本身类 ...

  3. 各种Oracle索引类型介绍

    逻辑上:Single column 单行索引Concatenated 多行索引Unique 唯一索引NonUnique 非唯一索引Function-based函数索引Domain 域索引 物理上:Pa ...

  4. ArcGIS10.6的新功能

    ArcMap 10.6 中引入了新的要素和功能,下面的章节将针对这些内容进行介绍. 要查看有关新特性的最新信息,请参阅 ArcMap web 帮助中的相关主题. 地理处理 3D Analyst 工具箱 ...

  5. 给你的 CentOS 7 安装中文支持

    今天给大家分享个给 CentOS 7 安装中文支持的方法,所谓“中文支持”目前明月观测到的是指命令行提示支持中文提示显示,还有就是 Vim 启动后看到的也是有中文提是的界面包括 Vim 内各种提示也会 ...

  6. linux性能采用工具oprofile使用

    1.先收藏几篇博文,先解决问题,周末继续. http://www.cnblogs.com/bangerlee/archive/2012/08/30/2659435.html http://blog.s ...

  7. [Canvas]炸弹人初成版

    试玩请点此下载代码,并使用浏览器打开index.html. 用方向键操作小人,空格键放炸弹,把敌人消灭算赢,被炸弹炸中或是碰到敌人算输. 图例: 源码: <!DOCTYPE html> & ...

  8. Android官方开发文档Training系列课程中文版:性能优化建议

    原文地址:http://android.xsoftlab.net/training/articles/perf-tips.html 本篇文章主要介绍那些能够提升总体性能的微小优化点.它与那些能突然改观 ...

  9. 使用vue.js路由踩到的一个坑Unknown custom element

    在配合require.js使用vue路由的时候,遇到了路由组件报错: “vue.js:597 [Vue warn]: Unknown custom element: <router-link&g ...

  10. Tumblr 架构设计

    英文原文:The Tumblr Architecture Yahoo Bought For A Cool Billion Dollars 最近的新闻中我们得知雅虎11亿美元收购了Tumblr: Yah ...