【问题标题】:How to post data on JSON web services in Windows Phone 8如何在 Windows Phone 8 中的 JSON Web 服务上发布数据
【发布时间】:2014-01-16 09:56:39
【问题描述】:

我想在 JSON Web 服务上发布数据以获取用户的登录凭据。

我使用下面的代码在 JSON 网络服务上发布数据。

private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        // Create a new HttpWebRequest object.
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://test/TestService/Service.svc/json/Login");

        request.ContentType = "application/json";
        //request.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0; Touch)";
       // request.CookieContainer = cookie;

        // Set the Method property to 'POST' to post data to the URI.
        request.Method = "POST";

        // start the asynchronous operation
        request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);

    }
private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
    {
            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;

            // End the operation
            Stream postStream = request.EndGetRequestStream(asynchronousResult);

            //postData value
            string postData = "{'userid': '" + textUserid.Text + "','password':'" + textPassword.Text + "'}";

            // Convert the string into a byte array. 
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Write to the request stream.
            postStream.Write(byteArray, 0, postData.Length);
            postStream.Close();

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

    }
private void GetResponseCallback(IAsyncResult asynchronousResult)
    {

            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
            // End the operation

            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);

            Stream streamResponse = response.GetResponseStream();

            StreamReader streamRead = new StreamReader(streamResponse);
            string read = streamRead.ReadToEnd();

            //respond from httpRequest
            //TextBox.Text = read;
            MessageBox.Show("Your Response: " + read);
            // Close the stream object
            streamResponse.Close();
            streamRead.Close();
            response.Close();
    } 

我在我的代码中导入以下命名空间

using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Text;

我正在调用 Button_Click_1 方法,从我的 Windows Phone 模拟器单击登录按钮。

但我收到此错误:

Error   1   'System.Net.WebRequest' does not contain a definition for 'GetRequestStream' and no extension method 'GetRequestStream' accepting a first argument of type 'System.Net.WebRequest' could be found (are you missing a using directive or an assembly reference?) E:\Users\maan\Documents\Visual Studio 2012\Projects\TestWebservice\TestWebservice\MainPage.xaml.cs  99  39  TestWebservice

Error   2   'System.Net.WebRequest' does not contain a definition for 'GetResponse' and no extension method 'GetResponse' accepting a first argument of type 'System.Net.WebRequest' could be found (are you missing a using directive or an assembly reference?)   E:\Users\maan\Documents\Visual Studio 2012\Projects\TestWebservice\TestWebservice\MainPage.xaml.cs  106 39  TestWebservice

请帮助我,我是开发 Windows 移动应用程序的新手。

【问题讨论】:

  • 您是否在应用清单文件中启用了“网络”功能?
  • 错误似乎是说应用程序找不到预期的方法。您有名为“GetRequestStream”或“GetResponse”的方法吗?您是否尝试将“GetRequestStreamCallback”重命名为“GetRequestStream”并将“GetResponseCallback”重命名为“GetResponse”?
  • @Ritesh 我已经在我的应用程序的 Web 服务参考参数中添加了我的 Web 服务 URL 以进行身份​​验证。

标签: c# json windows-phone-8


【解决方案1】:

请查看以下代码,希望对您有所帮助:

void sendRequest()
{
   Uri myUri = new Uri(http://www.yourwebsite.com);
   HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(myUri);
   myRequest.Method = AppResources.POST;
   myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), myRequest);
}

void GetRequestStreamCallback(IAsyncResult callbackResult)
{
    HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;

    // End the stream request operation
    Stream postStream = myRequest.EndGetRequestStream(callbackResult);

    // Create the post data
    string postData = "INSERT HERE THE JASON YOU WANT TO SEND";
    byte[] byteArray = Encoding.UTF8.GetBytes(postData);

    // Add the post data to the web request
    postStream.Write(byteArray, 0, byteArray.Length);
    postStream.Close();

    // Start the web request
    myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), myRequest);
}

 void GetResponsetStreamCallback(IAsyncResult callbackResult)
 {
     lib = new ApiLibrary();

     try
     {
         HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
         HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
         string result = "";
         using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
         {
             result = httpWebStreamReader.ReadToEnd();
         }

            string APIResult = result;

         }
         catch (Exception e)
         {

      }
   }

【讨论】:

  • 感谢您的回复,但是 ApiLibrary 类在哪里。
  • 你不需要 ApiLibrary 它只是我创建的东西。删除它
  • 它在代码行 "string postData = "{\"userid\":\"" + textUserid.Text + "\",\"password\" 处给出了用户代码未处理的 UnauthorizedAccessException 异常:\"" + textPassword.Text + "\"}";"
  • 将 textUserid.Text 和 textPAssword.text 值放入 state[] 然后在 postData = {\"userid\":\"" + Session["user"].ToString() + "\ ",\"密码\":\"" + 会话["密码"].ToString() + "\"}
  • 如果没有为请求设置内容会出现异常:myRequest.ContentType = "application/json";
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多