各种开发语言示例调用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”, ))