使用VB 以HttpPost方式 实现数据发送

Imports System.IO
Imports System.Xml
Imports System.Data
Imports System.Text.Encoding
Module Module1

    Sub Main()
        Dim str As String = "http://localhost/Post.aspx"
        Dim responseStr As String = PostRequest("xml内容", str)
        Console.WriteLine("http响应:")
        Console.WriteLine(responseStr)


    End Sub

    Public Function PostRequest(ByVal xmlRequest As String, ByVal postUrl As String) As String
        Dim xml As String = xmlRequest
        '实例化一个字符转码对象'
        Dim encoding As System.Text.Encoding = System.Text.Encoding.GetEncoding("utf-8")
        '创建一个web请求对象'
        Dim request As System.Net.WebRequest = System.Net.WebRequest.Create(postUrl)
        '设置请求方式为post'
        request.Method = "POST"
        '定义字节数组'
        Dim postdata() As System.Byte = encoding.GetBytes(xmlRequest)
        '设置request对象的请求字节的长度'
        request.ContentLength = postdata.Length
        '获取request对象的数据流'
        Dim requesstream As System.IO.Stream = request.GetRequestStream()
        '将数据内容填充到流中'
        requesstream.Write(postdata, 0, postdata.Length)
        '关闭流'
        requesstream.Close()
        '根据请求的request对象获取响应的response对象'
        Dim response As System.Net.WebResponse = request.GetResponse()
        '获取response数据流对象'
        Dim responsestream As StreamReader = New StreamReader(response.GetResponseStream())
        '将response流中的数据读取'
        Dim html As String = responsestream.ReadToEnd()
        requesstream.Close()
        response.Close()
        '返回本次请求的响应数据'
        Return html
    End Function

End Module
 
  
 
  


//http://localhost/Post.aspx的代码如下,是一个普通的aspx页面,
protected void Page_Load(object sender, EventArgs e)
    {
        ExecuteServer();
    }
    private void ExecuteServer()
    {
             StreamReader sr = new StreamReader(Request.InputStream);
            string strInput = sr.ReadToEnd();
            sr.Close();
            if (strInput.Contains("1001"))
            {
                Logger.LogInfo(String.Format("请求:{0}", strInput), "APITEST");
            }
            else
            {
                Logger.LogInfo(String.Format("请求:{0}", strInput));
            }
        this.Response.Write(strInput); //这里我们将收到的请求直接返回,不作处理,仅仅做事例而已
   }


你可能感兴趣的:(Web技术)