0

我一直在尝试HTTPRequest在我的 C# 项目中工作以获取GET请求,但我无法让它正常工作。下面是我的代码:

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();
    }

}

我目前得到的错误是:

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.

4

2 回答 2

2

我建议您使用功能强大的库“Microsoft HTTP 客户端库”,它需要 .NET 4 并与 WP7、WP8、Silverlight 4-5、Windows Store 应用程序、便携式类库一起使用。

您可以简单地从 NuGet 中添加它,并且非常简单地使用它。

这是 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..
            }
        }
于 2014-02-22T11:52:11.553 回答
1

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

您不能将“BeginGetRequestStream”方法与 GET 或 HEAD 请求一起使用(GET 是默认请求,也是您在第一个 HTTP 请求中执行的请求)。

正如您在代码的第二部分中所做的那样,更改为使用“BeginGetResponse”。

于 2013-02-11T15:09:56.517 回答