各種開發語言示例調用HTTP接口(示例中默認HTTP接口編碼為gb2312)


asp示例:

function getHTTPPage(strurl,data)
  on error resume next
  set http = Server.CreateObject("Msxml2.XMLHTTP")
  http.Open "POST",strurl, false
  http.setRequestHeader "Content-type:", "text/xml;charset=GB2312"
  Http.setRequestHeader   "Content-Type", "application/x-www-form-urlencoded"
  http.Send(data) 
  getHTTPPage=http.ResponseText
  set http=nothing
end function

C#示例:

 public static string PostData(string purl,string str)
          {
             try
             {
                 byte[] data = System.Text.Encoding.GetEncoding("GB2312").GetBytes(str);
                  // 准備請求
                  HttpWebRequest req = (HttpWebRequest)WebRequest.Create(purl);
 
                  //設置超時
                 req.Timeout = 30000;
                 req.Method = "Post";
                 req.ContentType = "application/x-www-form-urlencoded";
                 req.ContentLength = data.Length;
                 Stream stream = req.GetRequestStream();
                 // 發送數據
                stream.Write(data, 0, data.Length);
                stream.Close();
 
                  HttpWebResponse rep = (HttpWebResponse)req.GetResponse();
                  Stream receiveStream = rep.GetResponseStream();
                  Encoding encode = System.Text.Encoding.GetEncoding("GB2312");
                  // Pipes the stream to a higher level stream reader with the required encoding format.
                  StreamReader readStream = new StreamReader(receiveStream, encode);
 
                  Char[] read = new Char[256];
                  int count = readStream.Read(read, 0, 256);
                  StringBuilder sb = new StringBuilder("");
                  while (count > 0)
                  {
                      String readstr = new String(read, 0, count);
                      sb.Append(readstr);
                      count = readStream.Read(read, 0, 256);
                  }
 
                  rep.Close();
                  readStream.Close();
 
                  return sb.ToString();
 
              }
              catch (Exception ex)
              {
                  return "posterror";
              }
          }

Delphi示例:

function  HTTPwebservice(url:string):string;
var
    responseText:   WideString;
    xmlHttp:   OLEVariant;

begin
    try
        xmlHttp:=CreateOleObject('Msxml2.XMLHTTP');
        xmlHttp.open('GET',url,false);
        xmlHttp.send();
        responseText:=xmlHttp.responseText;
        if   xmlHttp.status='200'   then
        begin
        HTTPwebservice:=responseText;
        end;
        xmlHttp   :=   Unassigned;
    except
          exit;
    end;
end;

JAVA示例:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;


/**
* 發送短信基礎類
* @author administration
*
*/
public class SmsBase {
private String x_id="test";
private String x_pwd="123456";

public String SendSms(String mobile,String content) throws UnsupportedEncodingException{
Integer x_ac=10;//發送信息
HttpURLConnection httpconn = null;
String result="-20";
String memo = content.length()<70?content.trim():content.trim().substring(0, 70);
StringBuilder sb = new StringBuilder();
sb.append("URL?");
sb.append("id=").append(x_id);
sb.append("&pwd=").append(x_pwd);
sb.append("&to=").append(mobile);
sb.append("&content=").append(URLEncoder.encode(content, "gb2312"));

 try {
URL url = new URL(sb.toString());
httpconn = (HttpURLConnection) url.openConnection();
BufferedReader rd = new BufferedReader(new InputStreamReader(httpconn.getInputStream()));
result = rd.readLine();
rd.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
if(httpconn!=null){
httpconn.disconnect();
httpconn=null;
}

}
return result;
}
}

PHP示例:

<?php
Function SendSMS($url,$postStr)
{
 $ch = curl_init();
 $header = "Content-type: text/xml; charset=gb2312";
 curl_setopt($ch, CURLOPT_URL,$url);
 curl_setopt($ch, CURLOPT_POSTFIELDS, $postStr);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch, CURLOPT_POST, 1);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($ch, CURLOPT_HEADER, $header);
 $result = curl_exec($ch);
 curl_close($ch);
 $str = mb_convert_encoding($result, "gb2312", "utf-8");
 Return $str;
}

function sms_send($phone, $content) {
 $phoneList = $phone;
  $content = iconv("UTF-8","GB2312",$content); //如果亂碼換成這一句,兩者取其一即可urlencode($content);
  $userName = urlencode('帳號');
  $userPwd = '密碼';
  $url = "URL?";
  $postStr = "id=".$userName."&pwd=".$userPwd."&to=".$phoneList."&content=".$content."&time=";

  $res = SendSMS($url,$postStr);
  return substr($res,0,3) == 000 ? true : strval($content);
 
}
 echo sms_send('13129544822','短信內容');

?>

或者

<?php

$content= urlencode("你好啊短信內容");//內容
$uc=urlencode('帳號');
$pwd='密碼';
$msgid="12";
$callee="13129544822";//手機號
$sendurl="URL?";
$sdata="uc=".$uc."&pwd=".$pwd."&callee=".$callee."&cont=".$content."&msgid=".$msgid."&otime=";

$xhr=new COM("MSXML2.XMLHTTP");  
$xhr->open("POST",$sendurl,false);
$xhr->setRequestHeader ("Content-type:", "text/xml;charset=utf-8");
$xhr->setRequestHeader ("Content-Type", "application/x-www-form-urlencoded");
$xhr->send($sdata);  
echo $xhr->responseText;

?>

上面兩個是Windows—POST示例,下面這個是Linux-POST示例

<?php
function SendSMS($strMobile,$content){
   $url="URL?id=%s&pwd=%s&to=%s&content=%s&time=";
   $id = urlencode("賬號");
   $pwd = urlencode("密碼");
   $to = urlencode($strMobile);
   $content = iconv("UTF-8","GB2312",$content); //將utf-8轉為gb2312再發
   $rurl = sprintf($url, $id, $pwd, $to, $content);
   
   //初始化curl
      $ch = curl_init() or die (curl_error());
     //設置URL參數
      curl_setopt($ch,CURLOPT_URL,$rurl);
      curl_setopt($ch, CURLOPT_POST, 1);
      curl_setopt($ch, CURLOPT_HEADER, 0);
      //執行請求
      $result = curl_exec($ch) ;
      //取得返回的結果,並顯示
      echo $result;
      echo curl_error($ch);
      //關閉CURL
      curl_close($ch);
}
SendSMS($strMobile,$content);

?>

VB.NET示例:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        '/注意引入com   microsoft.xml.3.0
        Dim Send_URL, Http, getHTTPPage

        Send_URL = "URL?id=" + Trim(uid.Text) + "&pwd=" + Trim(pwd.Text) + "&to=" + mob.Text + "&content=" + msg.Text + "&time="
        Http = CreateObject("MSXML2.XMLHTTP")
        Http.Open("get", Send_URL, False)
        Http.send()

        getHTTPPage = Http.responseText
        backinfo.Text = getHTTPPage

    End Sub

Python示例:

import sys
import http
import urllib.request
import urllib.parse
import re
import time
class SendMessage:
    def main():
        url = 'URL?'
        uid = '帳號'
        pwd = '密碼'
        phone = input("Input the target telphone number:")
        content = input("Message:")
        url_address = url + 'id=' + urllib.parse.quote(uid.encode('gb2312')) + "&pwd=" + pwd + "&to=" + phone + "&content=" + urllib.parse.quote(content.encode("gb2312")) + "&time="
        answer = urllib.request.urlopen(url_address)
        data = answer.read()
        print(data)
    if __name__ == "__main__":
        main()

VB示例:

Private Sub Command1_Click()
  Set objXMLHTTP = CreateObject("MSXML2.XMLHTTP")
  objXMLHTTP.open "POST", "URL?", False 
  objXMLHTTP.setRequestHeader "Content-Type", "text/xml;charset=GB2312"
  objXMLHTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
  sdata = "id=" & uid & "&pwd=" & pwd & "&to=" & mobiles & "&content=" & message & "&time="    sdata = URLEncoding(sdata) 
  objXMLHTTP.send (sdata)
  返回值 = objXMLHTTP.ResponseText
  Set objXMLHTTP = Nothing
End Sub

易語言示例:

.程序集 窗口程序集1

.子程序 _發送_被單擊
.局部變量 obj, 文本型
.局部變量 http, 對象


' 如果群發,手機號碼格式以","隔開,結果返回000表示發送成功
obj = “URL?id=” + 賬戶編輯.內容 + “&pwd=” + 密碼編輯.內容 + “&to=” + 手機號碼編輯.內容 + “&content=” + 內容編輯.內容 + “&time=”
.如果真 (http.創建 (“Microsoft.XMLHTTP”, ))
    http.方法 (“open”, “GET”, obj, 假)
    http.寫屬性 (“Content-type”, “text/xml; charset=gb2312”)
    http.方法 (“send”, )
    編輯框1.內容 = 到文本 (http.讀文本屬性 (“responseText”, ))

 


免責聲明!

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



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