• 如何调用其他网站提供的接口


    这几天百度的结果,总结一下
    举例说明:某网站提供发送短信接口业务
    接口:SERVICE_URL变量 
    参数:username,pwd,mobiles,content
    返回:<ReturnInfo>resultcode</ReturnInfo>
    1、构建发送的xml或者其他形式的请求
    string postData = string.Format("ActionCode=Sms01&UserName=mine&Pwd=123&Mobiles={0}&Content={1}", strMobiles, strMessage+ "【客服中心】");
    并把请求转换成字节格式
    byte[] data = Encoding.Default.GetBytes(postData);
    2、 用HttpWebRequest来发送建立请求
    HttpWebRequest myrequest = (HttpWebRequest)WebRequest.Create(SERVICE_URL);
    3、向请求中写入请求的相关属性,也就是请求的头部格式(请求方法,版本类型,请求的字符编码,响应时间等)
                myrequest.Method = "POST";
                myrequest.ContentType = "application/x-www-form-urlencoded";
                myrequest.ContentLength = data.Length;
    4、 向请求中写入请求信息
       using (Stream datasteam = myrequest.GetRequestStream())
                {
                    datasteam.Write(data, 0, data.Length);
                    datasteam.Close();
                }
    5、得到响应请求
     HttpWebResponse myResponse = myrequest.GetResponse() as HttpWebResponse;
    6、读取响应中的数据
       HttpWebResponse myResponse = myrequest.GetResponse() as HttpWebResponse;
                using (StreamReader reader = new StreamReader(
                                                       myResponse.GetResponseStream()
                                                     , System.Text.Encoding.GetEncoding("utf-8")))
                {
                    response = reader.ReadToEnd();
                    xmlDoc.LoadXml(response);
                    reader.Close();
               }
    一般从网站返回的是一段xml格式的字符串
    7、把该字符串转换成xml格式,并取出当中的相关数据
    XmlDocument xmlDoc = new System.Xml.XmlDocument();
    string result = xmlDoc.SelectSingleNode("ReturnInfo").InnerText;
  • 相关阅读:
    IIS 和 各个协议
    Hibernate 框架基本知识
    各类主流框架及设计模式简介
    PHP微信公众开发笔记(七)
    PHP微信公众开发笔记(六)
    《Programming in Lua 3》读书笔记(二十七)
    《Programming in Lua 3》读书笔记(二十八)
    《Programming in Lua 3》读书笔记(二十六)
    PHP微信公众开发笔记(五)
    PHP微信公众开发笔记(四)
  • 原文地址:https://www.cnblogs.com/minesnil-forfaith/p/3806482.html
Copyright © 2020-2023  润新知