2012-12-31 62 views
0

我一直在試圖讓HTTPRequest在我的C#項目中工作,發現GET請求,我無法完成它的工作。下面是我的代碼:WP8上的HttpWebRequest

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.

+0

你能說說「不行」嗎?另外,你的URL搞砸了,你在'「http://mycompany.com」'和'「createtrip.php」' – Matthew

+0

之間沒有斜線。對不起,這是一個SO的臨時URL。我已經修改了主要帖子,並提供了更改和錯誤消息。 –

+0

您是否有堆棧跟蹤發生錯誤的位置? – Matthew

回答

1

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

不能使用方法 「BeginGetRequestStream」 用GET或HEAD請求(GET是第一個HTTP請求中默認的那個)。

更改爲使用「BeginGetResponse」,正如您在代碼的第二部分中所做的一樣。

+0

嗨,我想知道你是否已經解決了「繪製kdop」的問題,也許你想了很久這個問題。不過,如果你能幫我解決同樣的問題,我將非常感激。希望你的回覆。我的電子郵件是:[email protected]。 – tanglei

+0

我確實調用了BeginGetResponse spAuthReq.BeginGetResponse(新的AsyncCallback(GetResponsetStreamCallback),spAuthReq); 但我得到的答覆作爲System.Windows.ni.dll 中發生類型'System.Net.ProtocolViolationException'的第一次機會異常錯誤:具有此方法的請求不能有請求正文。 – obaid

2

我建議你使用功能強大的庫「Microsoft HTTP Client Libraries」,它需要.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.. 
      } 
     }