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(各种代码示例)

  • 相关阅读:
    Crystal Reports基础知识
    Dashboard与中国式报表的区别以及常见的Dashboard控件
    函数总结
    SQL Server 索引使用入门
    Linux+C 开发基础
    vi 开发环境~~转载
    linux mysql 基础操作使用
    sourceinsight 快捷键 转帖
    vi 利器
    fedora 7 英文环境 的汉字显示
  • 原文地址:https://www.cnblogs.com/hsuchan/p/3600527.html
Copyright © 2011-2022 走看看