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(各種代碼示例)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM