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

标签 c# web-services post windows-phone-8

我是 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";

关于c# - 将带有 XML 的 HTTP POST 请求发送到 Web 服务并在 C# 中读取 Windows 8 手机的响应数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18267832/

相关文章:

c# - 如何在 C# 中检查空的 .csv 扩展文件

c# - 基于 View 模型类型的边框触发器不起作用

iphone - App Store中iPhone应用程序的不同数据源

java - 在 Java 中为 SOLR curl 等效的 POST

c# - 如何抑制来自特定 dll 的警告

c# - 非主键上的 Entity Framework 关系

php - 在 Symfony2 中访问 HTTP PUT 数据

java - 在Http Web服务器中基于路径参数过滤请求

在 Flutter 中使用 Cookie 发布请求

Javascript 在 Firefox 中不发送 post 参数