简体   繁体   中英

HttpWebRequest on WP8

I have been trying to get HTTPRequest working in my C# Project for a GET request, and I can not quite get it to work. Below is my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using System.Windows;
using System.Diagnostics;
using System.Threading;

class MyClass 
{
    const string URL_PREFIX = "http://mycompany.com/";
    private HttpWebRequest objRequest = null;
    private static string myRequestData = string.Empty;
    private string urlAddress;


    public MyClass()
    {
        int member = 1;
        int startLoc = 1;
        int endLoc = 1;
        string starttime = "2012-01-01 00:00:00";
        string endtime = "2012-01-01 00:00:00";
        int rt = 1;
        string cmt = "Hello World";

        this.urlAddress = URL_PREFIX + string.Format(
        "createtrip.php?member={0}&startLoc={1}&endLoc={2}&starttime={3}&endtime={4}&rt={5}&cmt={6}"
        , member, startLoc, endLoc, starttime, endtime, rt, cmt);

        StringBuilder completeUrl = new StringBuilder(urlAddress);
        objRequest = (HttpWebRequest)WebRequest.Create(urlAddress);
        objRequest.ContentType = "application/x-www-form-urlencoded";

        objRequest.BeginGetRequestStream(new AsyncCallback(httpComplete), objRequest);
    }
    private static void httpComplete(IAsyncResult asyncResult)
    {
        HttpWebRequest objHttpWebRequest = (HttpWebRequest)asyncResult.AsyncState;
        // End the operation
        Stream postStream = objHttpWebRequest.EndGetRequestStream(asyncResult);
        // Convert the string into a byte array.
        byte[] byteArray = Encoding.UTF8.GetBytes(myRequestData);
        // Write to the request stream.
        postStream.Write(byteArray, 0, myRequestData.Length);
        postStream.Close();

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

    }
    private static void GetResponseCallback(IAsyncResult asyncResult)
    {
        HttpWebRequest objHttpWebRequest = (HttpWebRequest)asyncResult.AsyncState;
        HttpWebResponse objHttpWebResponse = (HttpWebResponse)objHttpWebRequest.EndGetResponse(asyncResult);
        Stream objStreamResponse = objHttpWebResponse .GetResponseStream();
        StreamReader objStreamReader = new StreamReader(objStreamResponse );
        string responseString = objStreamReader.ReadToEnd();            // Got response here
         MessageBox.Show("RESPONSE :" + responseString);
        // Close the stream object
        objStreamResponse .Close();
        objStreamReader.Close();
        objHttpWebResponse.Close();
    }

}

The error I am currently getting is:

An exception of type 'System.Collections.Generic.KeyNotFoundException' occurred in mscorlib.ni.dll and wasn't handled before a managed/native boundary A first chance exception of type 'System.Net.ProtocolViolationException' occurred in System.Windows.ni.dll Operation is not valid due to the current state of the object.

I suggest you to use the powerful library "Microsoft HTTP Client Libraries" that requires .NET 4 and works with WP7,WP8,Silverlight 4-5, Windows Store apps, Portable class libraries.

You can simply add it from NuGet, and very simply use it.

Here's an example of HTTP GET.

        private async Task PerformGet()
        {
            HttpClient client = new HttpClient();
            HttpResponseMessage response = await client.GetAsync(myUrlGet);
            if (response.IsSuccessStatusCode)
            {
                // if the response content is a byte array
                byte[] contentBytes = await response.Content.ReadAsByteArrayAsync();

                // if the response content is a stream
                Stream contentStream = await response.Content.ReadAsStreamAsync();

                // if the response content is a string (JSON or XML)
                string json = await response.Content.ReadAsStringAsync();

                // your stuff..
            }
        }

http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetrequeststream.aspx

You cannot use the method "BeginGetRequestStream" with a GET or HEAD request (GET is the default one and the one you're doing in the first HTTP request).

Change to use "BeginGetResponse" as you've already done in the second part of the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM