zoukankan      html  css  js  c++  java
  • java发送短信--httpclient方式

      最近头让我写个发送短信的java程序检测BI系统,检查数据库是否有异常发送,有则发送短信到头的手机里。这里我直说httpclient方式的get请求方式,并且已经有方式的短信的接口了,所以只要再加上参数即可实现,网上有好几种实现方式,我这个比较简单。

         具体实现代码如下:

         一、get方式

      //发送短信Get请求方式
        public void sendMSGByGet(String phone) throws HttpException, IOException{
            //传递参数  
            String param = "username="+USR+"&password="+PSD+"&phone="+phone+"&message="+URLEncoder.encode(MSG,  "GBK")+"&epid=105250&linkid=&subcode=123";//参数根据实际情况拼装
            System.out.println(param);
            HttpClient httpClient = new HttpClient();
            HttpMethod get = new GetMethod(URLSTR+"?"+param);  //get请求方式
            get.releaseConnection();  
            httpClient.executeMethod(get);//发送
            String response = get.getResponseBodyAsString();  //取得返回结果
            System.out.println(response);  
        }

      以上方式比较简单,需要注意的地方就是短信内容中文编码问题。

       二、post方式(这种方式比较普遍)

        实现代码如下:

        //发送短信post方式
        public void sendMSGByPost(String phone) throws HttpException, IOException{
            HttpClient client = new HttpClient();
            PostMethod post = new PostMethod(URLSTR);
            post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=gbk");//在头文件中设置转码
            NameValuePair[] data ={ //配置参数
                    new NameValuePair("username", USR),
                    new NameValuePair("password", PSD),
                    new NameValuePair("phone",phone),
                    new NameValuePair("message",MSG),
                    new NameValuePair("epid", EPID),
                    new NameValuePair("linkid",LINKID),
                    new NameValuePair("subcode",SUBCODE)
            };
            post.setRequestBody(data);
            client.executeMethod(post);//发送请求
            //以下为返回信息
            Header[] headers = post.getResponseHeaders();
            int statusCode = post.getStatusCode();//状态码
            System.out.println("statusCode:"+statusCode);
            for(Header h : headers)
            {
            System.out.println(h.toString());
            }
            String result = new String(post.getResponseBodyAsString().getBytes("gbk"));
            System.out.println(result);
            post.releaseConnection();
        }

       以上方式比较固定,其实很多都是用这种方式,有兴趣的可以试试中国网建的:http://www.smschinese.cn/api.shtml(各种代码示例)

  • 相关阅读:
    SQOOP的安装配置_Linux伊甸园开源社区24小时滚动更新开源资讯,全年无休!
    Cloudera's Hadoop Demo VM for CDH4 Cloudera Support
    海量文档查同或聚类问题 Locality Sensitive Hash 算法
    part 1: resemblance with the jaccard coefficient
    计算机科学中最重要的32个算法zz
    详细的tfidf构建过程实例(转)
    2012 Beijing Google Dev FastDay(11/03/2012) 移动新观察
    百度技术沙龙
    Hive官方手册翻译(Getting Started) 实践检验真理 51CTO技术博客
    《周末休闲吧》:教你如何玩车震——车震全程攻略!_周末休闲吧_百度空间
  • 原文地址:https://www.cnblogs.com/hsuchan/p/3600527.html
Copyright © 2011-2022 走看看