• C# wnform 请求http ( get , post 两种方式 )


    1.Get请求

    string strURL = "http://localhost/WinformSubmit.php?tel=11111&name=张三";
    System.Net.HttpWebRequest request;
    // 创建一个HTTP请求
    request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
    //request.Method="get";
    System.Net.HttpWebResponse response;
    response = (System.Net.HttpWebResponse)request.GetResponse();
    System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
    string responseText = myreader.ReadToEnd();
    myreader.Close();
    MessageBox.Show(responseText);

    2.Post请求

    string strURL = "http://localhost/WinformSubmit.php";
    System.Net.HttpWebRequest request;
    request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
    //Post请求方式
    request.Method = "POST";
    // 内容类型
    request.ContentType = "application/x-www-form-urlencoded";
    // 参数经过URL编码
    string paraUrlCoded = System.Web.HttpUtility.UrlEncode("keyword");
    paraUrlCoded += "=" + System.Web.HttpUtility.UrlEncode("多月");
    byte[] payload;
    //将URL编码后的字符串转化为字节
    payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
    //设置请求的 ContentLength
    request.ContentLength = payload.Length;
    //获得请 求流
    System.IO.Stream writer = request.GetRequestStream();
    //将请求参数写入流
    writer.Write(payload, 0, payload.Length);
    // 关闭请求流
    writer.Close();
    System.Net.HttpWebResponse response;
    // 获得响应流
    response = (System.Net.HttpWebResponse)request.GetResponse();
    System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
    string responseText = myreader.ReadToEnd();
    myreader.Close();
    MessageBox.Show(responseText);

    注:System.Web.HttpUtility.UrlEncode("多月"); 需要引用 System.web.dll

    WinformSubmit.php 代码如下:

     C# Code 
     
    <? php

    header ("content-Type: text/html; charset=Utf-8");
    echo mb_convert_encoding ("123abc娃哈哈""UTF-8""GBK");

    echo " ------ ";

    foreach ($_POST as $key => $value)
    {
        echo $key . '--' .$value ." ";
    }

    echo " ------- ";

    foreach ($_GET as $key => $value)
    {
        echo $key . '--' .$value ." ";
    }

    ? >

    =====================================================

    搞了2天,终于弄懂了一些Post的一些基础,在这里分享下,也给自己留个备忘

    项目分成两个 web(ASP.Net)用户处理请求,客户端(wpf/winform)发送请求

    1.web项目

    有两个页面

    SendPost.aspx(单纯发送数据给客户端)

    代码:

    public partial class SendPost : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {
    if (Request.RequestType == "POST")
    {
      //声明一个XMLDoc文档对象,LOAD()xml字符串
      XmlDocument doc = new XmlDocument();
      doc.LoadXml("<entity><version>1.2.0_2012_12_05</version></entity>");
      //把XML发送出去
      Response.Write(doc.InnerXml);
      Response.End();
    }
    }
    }

    Accept.aspx(接收数据并反馈发送会客户端)

    protected void Page_Load(object sender, EventArgs e)
    {
    if (Request.RequestType == "POST")
    {
      //接收并读取POST过来的XML文件流
      StreamReader reader = new StreamReader(Request.InputStream);
      String xmlData = reader.ReadToEnd();
      //把数据重新返回给客户端
      Response.Write(xmlData);
      Response.End();
    }
    }

    2.客户端项目:

    一个处理Post类

    public class PostHelp
    {
    public string GetWebContent(string url)
    {
    Stream outstream = null;
    Stream instream = null;
    StreamReader sr = null;
    HttpWebResponse response = null;
    HttpWebRequest request = null;
    // 要注意的这是这个编码方式,还有内容的Xml内容的编码方式
    Encoding encoding = Encoding.GetEncoding("UTF-8");
    byte[] data = encoding.GetBytes(url);

    // 准备请求,设置参数
    request = WebRequest.Create(url) as HttpWebRequest;
    request.Method = "POST";
    request.ContentType = "text/xml";
    //request.ContentLength = data.Length;

    outstream = request.GetRequestStream();
    outstream.Write(data, 0, data.Length);
    outstream.Flush();
    outstream.Close();
    //发送请求并获取相应回应数据

    response = request.GetResponse() as HttpWebResponse;
    //直到request.GetResponse()程序才开始向目标网页发送Post请求
    instream = response.GetResponseStream();

    sr = new StreamReader(instream, encoding);
    //返回结果网页(html)代码

    string content = sr.ReadToEnd();
    return content;
    }
    public string PostXml(string url, string strPost)
    {
    string result = "";

    StreamWriter myWriter = null;
    HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
    objRequest.Method = "POST";
    //objRequest.ContentLength = strPost.Length;
    objRequest.ContentType = "text/xml";//提交xml
    //objRequest.ContentType = "application/x-www-form-urlencoded";//提交表单
    try
    {
    myWriter = new StreamWriter(objRequest.GetRequestStream());
    myWriter.Write(strPost);
    }
    catch (Exception e)
    {
    return e.Message;
    }
    finally
    {
    myWriter.Close();
    }

    HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
    using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
    {
    result = sr.ReadToEnd();
    sr.Close();
    }
    return result;
    }
    }

    一个XML处理类

    public class XMLHelp
    {
    private XDocument _document;

    public XDocument Document
    {
    get { return _document; }
    set { _document = value; }
    }
    private string _fPath = "";

    public string FPath
    {
    get { return _fPath; }
    set { _fPath = value; }
    }

    /// <summary>
    /// 初始化数据文件,当数据文件不存在时则创建。
    /// </summary>
    public void Initialize()
    {
    if (!File.Exists(this._fPath))
    {
    this._document = new XDocument(
    new XElement("entity", string.Empty)
    );
    this._document.Save(this._fPath);
    }
    else
    this._document = XDocument.Load(this._fPath);
    }


    public void Initialize(string xmlData)
    {
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xmlData);

    this._document = XmlDocumentExtensions.ToXDocument(doc, LoadOptions.None);
    }
    /// <summary>
    /// 清空用户信息
    /// </summary>
    public void ClearGuest()
    {
    XElement root = this._document.Root;
    if (root.HasElements)
    {
    XElement entity = root.Element("entity");
    entity.RemoveAll();
    }
    else
    root.Add(new XElement("entity", string.Empty));
    }


    ///LYJ 修改
    /// <summary>
    /// 提交并最终保存数据到文件。
    /// </summary>

    public void Commit()
    {
    try
    {
    this._document.Save(this._fPath);
    }
    catch (Exception ex)
    {
    throw new Exception(ex.Message, ex);
    }
    }

    /// <summary>
    /// 更新
    /// </summary>
    public void UpdateQrState(string PId, string state)
    {
    XElement root = this._document.Root;
    XElement entity = root.Element("entity");

    IEnumerable<XElement> elements = entity.Elements().Where(p =>
    p.Attribute("PId").Value == PId);
    if (elements.Count() == 0)
    return;
    else
    {
    XElement guest = elements.First();
    guest.Attribute("FQdState").Value = state;
    guest.Attribute("FQdTime").Value = DateTime.Now.ToString();
    Commit();
    }
    }

    public IEnumerable<XElement> GetXElement()
    {
    XElement root = this._document.Root;
    IEnumerable<XElement> elements = root.Elements();
    return elements;
    }

     

    public DataTable GetEntityTable()
    {
    DataTable dtData = new DataTable();
    XElement root = this._document.Root;
    IEnumerable<XElement> elements = root.Elements();

    foreach (XElement item in elements)
    {
    dtData.Columns.Add(item.Name.LocalName);
    }
    DataRow dr = dtData.NewRow();
    int i = 0;
    foreach (XElement item in elements)
    {
    dr[i] = item.Value;
    i = i + 1;
    }
    dtData.Rows.Add(dr);
    return dtData;
    }

    }

    因为我这里用的是Linq操作XML所以多一个转换XML类

    public static class XmlDocumentExtensions
    {
    public static XDocument ToXDocument(this XmlDocument document)
    {
    return document.ToXDocument(LoadOptions.None);
    }

    public static XDocument ToXDocument(this XmlDocument document, LoadOptions options)
    {
    using (XmlNodeReader reader = new XmlNodeReader(document))
    {
    return XDocument.Load(reader, options);
    }
    }
    }

    客户端加个按钮,按钮代码

    private void button5_Click(object sender, RoutedEventArgs e)
    {
    PostHelp ph = new PostHelp();
    //请求,拿到数据
    string value = ph.GetWebContent("http://192.168.52.24:802/SendPost.aspx");
    //保存数据
    XMLHelp xh = new XMLHelp();
    xh.Document = XDocument.Parse(value);
    xh.FPath = Environment.CurrentDirectory + "\xml\a.xml";
    xh.Commit();
    //重新把数据拿出来,发送
    string a = xh.Document.ToString();
    string text = ph.PostXml("http://192.168.52.24:802/Accept.aspx", a);
    //根据得到数据显示
    this.textBlock1.Text = text;
    //把数据转换成DataTable,输出要的结果集
    DataTable dt = xh.GetEntityTable();
    MessageBox.Show(dt.Rows[0][0].ToString());

    }

    代码很多,思路虽然有写在注释里,但是还是不够清楚,我这里重新说一下

    1.首先是Post请求发送原理,客户端请求一个request,并把内容加到request中,发送到指定路径的页面,页面得到请求,返回数据,客户端再基于刚刚的request去GetResponse()得到返回数据

    2.另外一个是XML的操作,包括读取xml,把xml转成字符串用于发送,得到返回内容,保存到本地xml,再读取本地的xml,输出xml里面的值

    这里再提一下:想调试web,必须用vs自带的IIS虚拟器,在web项目设置个断点,然后运行,客户端请求的request的时候,web就会自动断到断点,就可以调试啦。

    不过用vs自带的虚拟器,会经常出现连接已断开的问题,等你调试好后,直接放到IIS中,或者不用vs自带的IIS虚拟器,直接设置项目指定到IIS位置,这种错误就不会出现了!

    这东西看简单,其实真的还是用了很多自己的时间,转载的童鞋,记得保留我的连接http://www.cnblogs.com/linyijia/archive/2013/03/08/2950210.html,不做纯粹的伸手党哦!

    ===============================================

    C#后台Post提交XML 及接收该XML的方法 http://www.cnblogs.com/hucaihao/p/3614503.html

     C# Code 
     
    //发送XML

    public void Send (object sender, System.EventArgs e)
    {
        string WebUrl = "http://localhost:4035/GetXML/GetDataSet";//换成接收方的URL
        RequestUrl (WebUrl, GetXml() );
    }
    public void RequestUrl (string url, string data) //发送方法
    {
        var request = WebRequest.Create (url);
        request.Method = "post";
        request.ContentType = "text/xml";
        request.Headers.Add ("charset:utf-8");
        var encoding = Encoding.GetEncoding ("utf-8");
        if (data != null)
        {
            byte[] buffer = encoding.GetBytes (data);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write (buffer, 0, buffer.Length);
        }
        else
        {
            //request.ContentLength = 0;
        }
        //using (HttpWebResponse wr = request.GetResponse() as HttpWebResponse)
        //{
        //    using (StreamReader reader = new StreamReader(wr.GetResponseStream(), encoding))
        //    {
        //        return reader.ReadToEnd();
        //    }
        //}
    }

    public string GetXml() //要发送的XML
    {
        StringBuilder strBuilder = new StringBuilder();
        strBuilder.Append ("<?xml version="1.0" encoding="UTF-8"?>");
        strBuilder.Append ("<root>");
        strBuilder.Append ("<customer_id>123</customer_id>");
        strBuilder.Append ("<terminal_code>10444441</terminal_code>");
        strBuilder.Append ("<customer_mobile>13464537875</customer_mobile>");
        strBuilder.Append ("<customer_name>张三丰</customer_name>");
        strBuilder.Append ("<relationship>母子</relationship>");
        strBuilder.Append ("<baby_name>张国立</baby_name>");
        strBuilder.Append ("<baby_sex>1</baby_sex>");
        strBuilder.Append ("<baby_birthday>2012-06-08</baby_birthday>");
        strBuilder.Append ("<province>浙江</province>");
        strBuilder.Append ("<region>杭州</region>");
        strBuilder.Append ("<county>建德</county>");
        strBuilder.Append ("<address>西湖区文三路158号</address>");
        strBuilder.Append ("<feedback>1</feedback>");
        strBuilder.Append ("</root>");
        return strBuilder.ToString();
    }

    //接收XML

    public void GetDataSet (string text)
    {
        try
        {
            Stream inputstream = Request.InputStream;
            byte[] b = new byte[inputstream.Length];
            inputstream.Read (b, 0, (int) inputstream.Length);
            string inputstr = UTF8Encoding.UTF8.GetString (b);
            XmlDocument d = new XmlDocument();
            d.LoadXml (inputstr);
        }
        catch
        {

        }
    }

    ========================================

    C#中使用POST发送XML

     C# Code 
     
    /// C#  POST 发送XML
    /// </summary>
    /// <param name="url">目标Url</param>
    /// <param name="strPost">要Post的字符串(数据)</param>
    /// <returns>服务器响应</returns>
    private string PostXml (string url, string strPost)
    {
        string result = string.Empty;
        //Our postvars
        //ASCIIEncoding.ASCII.GetBytes(string str)
        //就是把字符串str按照简体中文(ASCIIEncoding.ASCII)的编码方式,
        //编码成 Bytes类型的字节流数组;
        // 要注意的这是这个编码方式,还有内容的Xml内容的编码方式,如果没有注意对应会出现文末的错误
        byte[] buffer = Encoding.UTF8.GetBytes (strPost);
        StreamWriter myWriter = null;
        //根据url创建HttpWebRequest对象
        //Initialisation, we use localhost, change if appliable
        HttpWebRequest objRequest = (HttpWebRequest) WebRequest.Create (url);
        //Our method is post, otherwise the buffer (postvars) would be useless
        objRequest.Method = "POST";
        //The length of the buffer (postvars) is used as contentlength.
        //Set the content length of the string being posted.
        objRequest.ContentLength = buffer.Length;
        //We use form contentType, for the postvars.
        //Set the content type of the data being posted.
        objRequest.ContentType = "text/xml";//提交xml
        //objRequest.ContentType = "application/x-www-form-urlencoded";//提交表单
        try
        {
            //We open a stream for writing the postvars
            myWriter = new StreamWriter (objRequest.GetRequestStream() );
            //Now we write, and afterwards, we close. Closing is always important!
            myWriter.Write (strPost);
        }
        catch (Exception e)
        {
            return e.Message;
        }
        finally
        {
            myWriter.Close();
        }
        //读取服务器返回信息
        //Get the response handle, we have no true response yet!
        //本文URL:http://www.bianceng.cn/Programming/csharp/201410/45576.htm
        HttpWebResponse objResponse = (HttpWebResponse) objRequest.GetResponse();
        //using作为语句,用于定义一个范围,在此范围的末尾将释放对象
        using (StreamReader sr = new StreamReader (objResponse.GetResponseStream() ) )
        {
            //ReadToEnd适用于小文件的读取,一次性的返回整个文件
            result = sr.ReadToEnd();
            sr.Close();
        }
        return result;
    }

    背景:

    我发送的是encoding='UTF-8'格式的xml字符串,但一开始我使用的是

    Encoding.Unicode.GetBytes(strPost)或者Default、ASCII均会提示错误。

    修改字符编码格式后,成功!所以要根据发送的格式选取合适的方法。

    注意:

    该函数可以发送xml到用友那边,但返回信息中中文字符为乱码。

    这个函数也可以实现同样的功能却避免了乱码问题

    详细过程及代码如下:

    1、创建httpWebRequest对象,HttpWebRequest不能直接通过new来创建,只能通过WebRequest.Create(url)的方式来获得。 WebRequest是获得一些应用层协议对象的一个统一的入口(工厂模式),它根据参数的协议来确定最终创建的对象类型。

    2、初始化HttpWebRequest对象,这个过程提供一些http请求常用的标头属性:agentstring,contenttype等,其中agentstring比较有意思,它是用来识别你用的浏览器名字的,通过设置这个属性你可以欺骗服务器你是一个IE,firefox甚至是mac里面的safari。很多认真设计的网站都会根据这个值来返回对不同浏览器特别优化的代码。

    3、附加要POST给服务器的数据到HttpWebRequest对象,附加POST数据的过程比较特殊,它并没有提供一个属性给用户存取,需要写入HttpWebRequest对象提供的一个stream里面。

    4、读取服务器的返回信息,读取服务器返回的时候,要注意返回数据的encoding,如果我们提供的解码类型不对,会造成乱码,比较常见的是utf-8和gb2312。通常,网站会把它编码的方式放在http header里面,如果没有,我们只能通过对返回二进制值的统计方法来确定它的编码方式。

  • 相关阅读:
    系统运行缓慢,CPU 100%,以及Full GC次数过多问题的排查思路
    微阵列杂交(Microarray Hybridization)
    autocad2018安装笔记
    java基础 大数类
    leetCode 23
    java语言基础 String类
    定时任务cronie
    Linux-vim使用操作大全
    计网期末复习题目
    操作系统期末复习题
  • 原文地址:https://www.cnblogs.com/qq260250932/p/5475386.html
Copyright © 2020-2023  润新知