簡體   English   中英

使用XML將HTTP POST請求發送到Web服務並在Windows 8手機的C#中讀取響應數據

[英]Sending HTTP POST Request with XML to a web service and reading response data in C# for windows 8 phone

我是Windows 8手機開發的新手。 我想將aync HTTP POST請求發送到在請求正文中帶有一些標頭和XML的PHP​​ Web服務。

另外,我想閱讀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";

如果您要做的只是獲取已經生成的XML並將其作為內容添加到現有請求中,那么您將需要能夠寫入請求流。 我並不特別在意獲取請求流的股票模型,因此,我建議使用以下擴展名,使您的生活更輕松一些:

public static class Extensions
{
    public static System.Threading.Tasks.Task<System.IO.Stream> GetRequestStreamAsync(this System.Net.HttpWebRequest wr)
    {
        if (wr.ContentLength < 0)
        {
            throw new InvalidOperationException("The ContentLength property of the HttpWebRequest must first be set to the length of the content to be written to the stream.");
        }

        var tcs = new System.Threading.Tasks.TaskCompletionSource<System.IO.Stream>();

        wr.BeginGetRequestStream((result) =>
        {
            var source = (System.Net.HttpWebRequest)result.AsyncState;

            tcs.TrySetResult(source.EndGetRequestStream(result));

        }, wr);

        return tcs.Task;
    }
}

在這里,增加您的SendRequest方法:

public static void SendRequest(string myXml)
{
    HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.CreateHttp("http://mytestserver.com/Test.php");
    webRequest.Method = "POST";
    webRequest.Headers["SOURCE"] = "WinApp";

    // Might not hurt to specify encoding here
    webRequest.ContentType = "text/xml; charset=utf-8";

    // ContentLength must be set before a stream may be acquired
    byte[] content = System.Text.Encoding.UTF8.GetBytes(myXml);
    webRequest.ContentLength = content.Length;

    var reqStream = await webRequest.GetRequestStreamAsync();
    reqStream.Write(content, 0, content.Length);

    var response = await httpRequest(webRequest);
}

如果您要訪問的服務是SOAP服務,則可以通過讓IDE為您生成客戶端類來進一步簡化此服務。 有關如何執行操作的更多信息,請參見MSDN文章 但是,如果該服務沒有Web服務定義語言(WSDL)文檔,則該方法將無法為您提供幫助。

您可以使用Windows Phone 8中的HTTP客戶端庫,並以與Windows 8相同的方式使用客戶端。

首先,從Nuget獲取HTTP客戶端庫 現在,執行POST呼叫

HttpClient client = new HttpClient();
HttpContent httpContent = new StringContent("my content: xml, json or whatever");
httpContent.Headers.Add("name", "value");

HttpResponseMessage response = await client.PostAsync("uri", httpContent);
if (response.IsSuccessStatusCode)
{
    // DO SOMETHING
}

我希望這可以幫助你 :)

我已經以其他方式解決了這個問題。

    class HTTPReqRes
    {
    private static HttpWebRequest webRequest;

    public static void SendRequest()
    {
        webRequest = (HttpWebRequest)HttpWebRequest.CreateHttp("https://www.mydomain.com");
        webRequest.Method = "PUT";
        webRequest.ContentType = "text/xml; charset=utf-8";
        webRequest.Headers["Header1"] = "Header1Value";



        String myXml = "<Roottag><info>test</info></Roottag>";

        // Convert the string into a byte array. 
        byte[] byteArray = Encoding.UTF8.GetBytes(myXml);

        webRequest.ContentLength = byteArray.Length;

        // start the asynchronous operation
        webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);                  
        //webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
    }

    private static void GetRequestStreamCallback(IAsyncResult asynchronousResult)
    {
        HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;

        // End the operation
        Stream postStream = request.EndGetRequestStream(asynchronousResult);

        String myXml = <Roottag><info>test</info></Roottag>";

        // Convert the string into a byte array. 
        byte[] byteArray = Encoding.UTF8.GetBytes(myXml);

        // Write to the request stream.
        postStream.Write(byteArray, 0, byteArray.Length);
        postStream.Close();

        // Start the asynchronous operation to get the response
        request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
    }

    private static void GetResponseCallback(IAsyncResult asynchronousResult)
    {
        HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;

        // End the operation
        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
        Stream streamResponse = response.GetResponseStream();
        StreamReader streamRead = new StreamReader(streamResponse);
        string responseString = streamRead.ReadToEnd();
        System.Diagnostics.Debug.WriteLine(responseString);
        // Close the stream object
        streamResponse.Close();
        streamRead.Close();

        // Release the HttpWebResponse
        response.Close();
    }
}

這可以完美解決我的問題,在HTTP請求中發送XML,並在響應中從Web服務接收XML。

我建議使用RestSharp庫。 您可以在此處找到示例請求。

這就是我用的。 確實很簡單,將WindowsPhonePostClient.dll添加到您的引用中(如果不能,請首先嘗試通過properties-> unblock取消阻止文件),然后使用以下代碼:

private void Post(string YourUsername, string Password)
{
        Dictionary<string, object> parameters = new Dictionary<string, object>();
        parameters.Add("User", YourUsername);
        parameters.Add("Password", Password);
        PostClient proxy = new PostClient(parameters);
        proxy.DownloadStringCompleted += proxy_UploadDownloadStringCompleted;

        proxy.DownloadStringAsync(new Uri("http://mytestserver.com/Test.php",UriKind.Absolute));

} 


private void proxy_UploadDownloadStringCompleted(object sender,WindowsPhonePostClient.DownloadStringCompletedEventArgs e)
{
    if (e.Error == null)
        MessageBox.Show(e.Result.ToString());
}     

您需要創建對Web服務wsdl的引用,也可以嘗試按此處詳細說明手動進行操作: https : //stackoverflow.com/a/1609427/2638872

//The below code worked for me. I receive xml response back. 
private void SendDataUsingHttps()
{                   
     WebRequest req = null;       
     WebResponse rsp = null;
     string fileName = @"C:\Test\WPC\InvoiceXMLs\123File.xml";                  string uri = "https://service.XYZ.com/service/transaction/cxml.asp";
            try
            {
                if ((!string.IsNullOrEmpty(uri)) && (!string.IsNullOrEmpty(fileName)))
                {
                    req = WebRequest.Create(uri);
                    //req.Proxy = WebProxy.GetDefaultProxy(); // Enable if using proxy
                    req.Method = "POST";        // Post method
                    req.ContentType = "text/xml";     // content type
                    // Wrap the request stream with a text-based writer                  
                    StreamWriter writer = new StreamWriter(req.GetRequestStream());
                    // Write the XML text into the stream
                    StreamReader reader = new StreamReader(file);
                    string ret = reader.ReadToEnd();
                    reader.Close();
                    writer.WriteLine(ret);
                    writer.Close();
                    // Send the data to the webserver
                    rsp = req.GetResponse();
                    HttpWebResponse hwrsp = (HttpWebResponse)rsp;
                    Stream streamResponse = hwrsp.GetResponseStream();
                    StreamReader streamRead = new StreamReader(streamResponse);
                    string responseString = streamRead.ReadToEnd();                    
                    rsp.Close();
                }
            }
            catch (WebException webEx) { }
            catch (Exception ex) { }
            finally
            {
                if (req != null) req.GetRequestStream().Close();
                if (rsp != null) rsp.GetResponseStream().Close();
            }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM