2012-12-31 4 views
0

GET 요청에 대한 내 C# 프로젝트에서 HTTPRequest을 작동 시키려고 노력 중이며 제대로 작동하지 않습니다.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

사이에 슬래시가 없습니다. 죄송합니다. 지금은 임시 URL입니다. 나는 그 변화와 나의 오류 메시지로 메인 포스트를 편집했다. –

+0

오류가 발생한 위치에 대한 스택 추적이 있습니까? – Matthew

답변

1

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

당신은 GET (GET 또는 HEAD 요청 방법 "BeginGetRequestStream"을 사용할 수 없습니다 기본 HTTP 요청이고 첫 번째 HTTP 요청에서 수행중인 HTTP 요청입니다).

코드의 두 번째 부분에서 이미 수행 한 것처럼 "BeginGetResponse"를 사용하도록 변경하십시오.

+0

안녕하세요, 저는 "그림 그리기"에 관한 문제를 해결했는지 궁금합니다. 아마도이 질문에 대해 생각하는 것이 오랜 시간 일 것입니다. 그것은 동일한 문제를 해결하는 데 도움이 될 수 있다면 매우 감사하게 생각합니다. 유감스럽게 생각합니다. 내 이메일 : [email protected] – tanglei

+0

BeginGetResponse spAuthReq.BeginGetResponse (새 AsyncCallback (GetResponsetStreamCallback), spAuthReq)를 호출했습니다. 하지만 System.Windows.ni.dll에서 'System.Net.ProtocolViolationException'형식의 첫 번째 예외가 발생했습니다. 오류 :이 메서드는 요청 본문을 가질 수 없습니다. – obaid

2

.NET 4가 필요하며 WP7, WP8, Silverlight 4-5, Windows Store 응용 프로그램, 휴대용 클래스 라이브러리에서 작동하는 강력한 라이브러리 "Microsoft HTTP Client Libraries"를 사용하는 것이 좋습니다.

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.. 
      } 
     }