2011-11-16 67 views
3

我是Windows Phone 7應用程序開發的新手。我正在嘗試使用POST方法在我的程序中調用一個URL,該方法需要一些參數。成功發佈後,我應該以JSON格式獲得響應。但我沒有得到答覆。我使用的代碼是:在WP7中調用POST方法

public void Submit() 
    { 
     // Prepare web request... 
     HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(new Uri(someUrl, UriKind.Absolute)); 
     myRequest.Method = "POST"; 
     myRequest.ContentType = string.Format("multipart/form-data; boundary={0}", boundary); 

     myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), myRequest); 
    } 


    public string url { get; set; } 
    private Dictionary<string, string> _parameters = new Dictionary<string, string>(); 

    public Dictionary<string, string> parameters 
    { 
     get { return _parameters; } 
     set { _parameters = value; } 
    } 

    string boundary = "----------" + DateTime.Now.Ticks.ToString(); 


    private void GetRequestStreamCallback(IAsyncResult asynchronousResult) 
    { 
     HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState; 
     Stream postStream = request.EndGetRequestStream(asynchronousResult); 
     parameters.Add("userid", "0"); 
     parameters.Add("locationid", "0"); 
     writeMultipartObject(postStream, parameters); 
     postStream.Close(); 

     request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request); 
    } 

    private void GetResponseCallback(IAsyncResult asynchronousResult) 
    { 
     HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState; 
     HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult); 
     Stream streamResponse = response.GetResponseStream(); 
     StreamReader streamRead = new StreamReader(streamResponse); 
     streamResponse.Close(); 
     streamRead.Close(); 
     // Release the HttpWebResponse 
     response.Close(); 
    } 

    public void writeMultipartObject(Stream stream, object data) 
    { 
     StreamWriter writer = new StreamWriter(stream); 
     if (data != null) 
     { 
      foreach (var entry in data as Dictionary<string, string>) 
      { 
       WriteEntry(writer, entry.Key, entry.Value); 
      } 
     } 
     writer.Write("--"); 
     writer.Write(boundary); 
     writer.WriteLine("--"); 
     writer.Flush(); 
    } 

    private void WriteEntry(StreamWriter writer, string key, object value) 
    { 
     if (value != null) 
     { 
      writer.Write("--"); 
      writer.WriteLine(boundary); 
      if (value is byte[]) 
      { 
       byte[] ba = value as byte[]; 

       writer.WriteLine(@"Content-Disposition: form-data; name=""{0}""; filename=""{1}""", key, "sentPhoto.jpg"); 
       writer.WriteLine(@"Content-Type: application/octet-stream"); 
       //writer.WriteLine(@"Content-Type: image/jpeg"); 
       writer.WriteLine(@"Content-Length: " + ba.Length); 
       writer.WriteLine(); 
       writer.Flush(); 
       Stream output = writer.BaseStream; 

       output.Write(ba, 0, ba.Length); 
       output.Flush(); 
       writer.WriteLine(); 
      } 
      else 
      { 
       writer.WriteLine(@"Content-Disposition: form-data; name=""{0}""", key); 
       writer.WriteLine(); 
       writer.WriteLine(value.ToString()); 
      } 
     } 
    } 

我找不到真正的問題。有人幫我解決問題嗎?

+0

嗨獲得,你能否確認Web服務器響應您的張貼?在你的代碼中,似乎你正在正確地執行你的請求,但你似乎沒有在請求的主體中添加任何數據。這是一個POST應該做的事情。服務器可能不接受您的請求。 – ajmccall

回答

0

我得到了解決辦法爲:

{ 
     Dictionary<string, object> param = new Dictionary<string, object>(); 
     param.Add(DataHolder.USER_ID, "0"); 
     param.Add(DataHolder.DEFAULT_LOCATION_ID, "0"); 
     PostClient proxy = new PostClient(param); 
     proxy.DownloadStringCompleted += new PostClient.DownloadStringCompletedHandler(proxy_DownloadStringCompleted);   
     proxy.DownloadStringAsync(new Uri(DataHolder.mainConfigFetchUrl, UriKind.Absolute)); 





    } 

    void proxy_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) 
    { 
     if (e.Error == null) 
     { 
      //Process the result... 
      string data = e.Result; 
     } 
    } 

對於PostClient我們需要一個WindowsPhonePostClient.dll可以從http://postclient.codeplex.com/

0

這個例子來自http://northernlights.codeplex.com

/// <summary> 
    /// Send error report (exception) to HTTP endpoint. 
    /// </summary> 
    /// <param name="uri">The Endpoint to report to.</param> 
    /// <param name="exception">Exception to send.</param> 
    public void SendExceptionToHttpEndpoint(string uri, ExceptionContainer exception) 
    { 
     if (!this.AllowAnonymousHttpReporting) 
     { 
      return; 
     } 

     try 
     { 
      HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri); 
      webRequest.Method = "POST"; 
      webRequest.ContentType = "application/x-www-form-urlencoded"; 

      webRequest.BeginGetRequestStream(
       r => 
       { 
        try 
        { 
         HttpWebRequest request1 = (HttpWebRequest)r.AsyncState; 
         Stream postStream = request1.EndGetRequestStream(r); 

         string info = string.Format("{0}{1}{2}{1}AppVersion: {3}{1}", exception.Message, Environment.NewLine, exception.StackTrace, exception.AppVersion); 

         string postData = "&exception=" + HttpUtility.UrlEncode(info); 
         byte[] byteArray = Encoding.UTF8.GetBytes(postData); 

         postStream.Write(byteArray, 0, byteArray.Length); 
         postStream.Close(); 

         request1.BeginGetResponse(
          s => 
          { 
           try 
           { 
            HttpWebRequest request2 = (HttpWebRequest)s.AsyncState; 
            HttpWebResponse response = (HttpWebResponse)request2.EndGetResponse(s); 

            Stream streamResponse = response.GetResponseStream(); 
            StreamReader streamReader = new StreamReader(streamResponse); 
            string response2 = streamReader.ReadToEnd(); 
            streamResponse.Close(); 
            streamReader.Close(); 
            response.Close(); 
           } 
           catch 
           { 
           } 
          }, 
         request1); 
        } 
        catch 
        { 
        } 
       }, 
      webRequest); 
     } 
     catch 
     { 
     } 
    } 

它表明你如何發佈。

+0

你爲什麼捕捉並丟棄異常?忽略這些例外是否安全? –

+0

在這種情況下,POST成功並不重要。此代碼用於向Windows Phone應用程序的開發者報告以前的異常。你可以在這裏添加你自己的異常處理。 – invalidusername

0

WP7附帶了「反應性擴展」,這對一般的異步交互很有幫助。此示例http://wp7guide.codeplex.com顯示瞭如何將它用於HTTP Posts(以及其他內容)

注意:該示例適用於相當先進的應用程序,並且旨在顯示許多其他內容,例如使用MVVM模式的單元測試等。它可能比你需要的更復雜。