Skip to main content
 首页 » 编程设计

c#之将带有 XML 的 HTTP POST 请求发送到 Web 服务并在 C# 中读取 Windows 8 手机的响应数据

2024年01月16日2798°冷暖

我是 Windows 8 手机开发的新手。我想向 PHP Web 服务发送一个 aync HTTP POST 请求,请求正文中有一些 header 和 XML。

另外,我想阅读 PHP Web 服务发回的响应。

请指导我,我怎样才能实现上述两件事。

到目前为止我所尝试的我在下面给出

// Main begins program execution. 
    public static void SendRequest() 
    { 
 
        HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.CreateHttp("http://mytestserver.com/Test.php"); 
        webRequest.Method = "POST"; 
        webRequest.ContentType = "text/xml"; 
        webRequest.Headers["SOURCE"] = "WinApp"; 
 
        var response = await httpRequest(webRequest);            
 
    } 
 
    public static async Task<string> httpRequest(HttpWebRequest request) 
    { 
        string received; 
 
        using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null))) 
        { 
            using (var responseStream = response.GetResponseStream()) 
            { 
                using (var sr = new StreamReader(responseStream)) 
                { 
 
                    received = await sr.ReadToEndAsync(); 
 
                    MessageBox.Show(received.ToString()); 
                } 
            } 
        } 
        return received; 
    } 

我可以使用上面的代码发送请求。我只需要知道如何将请求正文中的 XML 发送到我的 Web 服务。

请您参考如下方法:

对于设置文件并接收服务器响应,我使用它来发送 .csv 文件:

首先我初始化一个 POST 请求:

/// <summary> 
///     Initialize the POST HTTP request. 
/// </summary> 
public void SentPostReport() 
{ 
    string url = "http://MyUrlPerso.com/"; 
    Uri uri = new Uri(url); 
    // Create a boundary for HTTP request. 
    Boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x"); 
 
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); 
    request.ContentType = "multipart/form-data; boundary=" + Boundary; 
    request.Method = "POST"; 
    request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), est); 
        allDone.WaitOne(); 
} 

初始化请求后,我发送文件的不同部分(页眉 + 内容 + 页脚)。
/// <summary> 
///     Send a File with initialized request. 
/// </summary> 
private void GetRequestStreamCallback(IAsyncResult asynchronousResult) 
{ 
    string contentType = "binary"; 
    string myFileContent = "one;two;three;four;five;"; // CSV content. 
    HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState; 
    Stream memStream = request.EndGetRequestStream(asynchronousResult); 
    byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes("\r\n--" + Boundary + "\r\n"); 
 
    memStream.Write(boundarybytes, 0, boundarybytes.Length); 
 
    // Send headers. 
    string headerTemplate = "Content-Disposition: form-data; "; 
    headerTemplate += "name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: " + contentType + "\r\n\r\n"; 
    string fileName = "MyFileName.csv"; 
    string header = string.Format(headerTemplate, "file", fileName); 
    byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header); 
    memStream.Write(headerbytes, 0, headerbytes.Length); 
 
    byte[] contentbytes = System.Text.Encoding.UTF8.GetBytes(myFileContent); 
 
    // send the content of the file. 
    memStream.Write(contentbytes, 0, contentbytes.Length); 
 
    // Send last boudary of the file ( the footer) for specify post request is finish. 
    byte[] boundarybytesend = System.Text.Encoding.UTF8.GetBytes("\r\n--" + Boundary + "--\r\n"); 
    memStream.Write(boundarybytesend, 0, boundarybytesend.Length); 
    memStream.Flush(); 
    memStream.Close(); 
 
    allDone.Set(); 
    // Start the asynchronous operation to get the response 
    request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request); 
} 

而且,Finnaly,我得到了响应服务器响应,表明文件已被传输。
/// <summary> 
///     Get the Response server. 
/// </summary> 
private static void GetResponseCallback(IAsyncResult asynchronousResult) 
{ 
    HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState; 
 
    try 
    { 
        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult); 
        Stream streamResponse = response.GetResponseStream(); 
        StreamReader streamRead = new StreamReader(streamResponse); 
 
        string responseString = streamRead.ReadToEnd(); // this is a response server. 
 
        // Close the stream object 
        streamResponse.Close(); 
        streamRead.Close(); 
 
        // Release the HttpWebResponse 
        response.Close(); 
    } 
        catch (Exception ex) 
        { 
            // error. 
        } 
    } 

此示例适用于 Windows Phone 7 和 Windows Phone 8。
这是用于发送 .csv 内容。您可以调整此代码以发送 Xml 内容。
只更换
string myFileContent = "one;two;three;four;five;"; // CSV content. 
string fileName = "MyFileName.csv"; 

通过您的 XML
string myFileContent = "<xml><xmlnode></xmlnode></xml>"; // XML content. 
string fileName = "MyFileName.xml";