Http Post Get Response Error for Windows Phone 8

被刻印的时光 ゝ 提交于 2020-01-15 11:49:09

问题


I am reposting this second question from my original post (Http Post for Windows Phone 8) because my primary question was alreayd answered.

This is my updated code with the help of @Hunter McMillen.. I am now trying to get a responseCallback from the server. The problem is the GetResponseCallback => (HttpWebResponse)httpWebRequest.EndGetResponse(GetResponseCallback) line in the second using statement, it is displaying

An exception of type 'System.Net.WebException' occurred in System.Windows.ni.dll but was not handled in user code

If there is a handler for this exception, the program may be safely continued.

This error occured before when I was using the first example. Does anyone know how to solve this?

  private static async void HttpPostData(){
            string url = "http://www.mytunnel.com/api/purchases";
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.ContentType = "text/plain";
            //httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            httpWebRequest.AllowWriteStreamBuffering = true;
            httpWebRequest.Method = "POST";
            //httpWebRequest.ContentLength = jsonAsBytes.Length;

        try{
            using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream, httpWebRequest.EndGetRequestStream, null))
            {
                byte[] jsonAsBytes = Encoding.UTF8.GetBytes("{ \"data\" : \"json\" }");
                await stream.WriteAsync(jsonAsBytes, 0, jsonAsBytes.Length);
            }
        }
        catch (Exception e) { Debug.WriteLine(e.Message); }

        httpWebRequest.BeginGetResponse(new AsyncCallback(ReadWebRequestCallback), httpWebRequest);
    }

    private static void ReadWebRequestCallback(IAsyncResult callbackResult)
    { 
        HttpWebRequest myRequest = callbackResult.AsyncState as HttpWebRequest;

        try
        {
            HttpWebResponse response = myRequest.EndGetResponse(callbackResult) as HttpWebResponse;
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                String s = sr.ReadToEnd();
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => { MessageBox.Show(s); });
            }
        }
        catch (WebException webExcp)
        {
            System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => { MessageBox.Show(webExcp.ToString()); });
        }
    }

回答1:


I ended up using WebClient instead. The code is much cleaner and I read the comments at the bottom from the sample link I provided in the original post. The sample form Microsoft was actually copied from a stackoverflow post.. and it doesn't work (don't trust MS docs).

Here's my code and a tutorial link (http://www.daveamenta.com/2008-05/c-webclient-usage/)for everyone having the same problem.. Thumbs up for me please if this helps you.

  private void httpPostData()
        {
            WebClient webClient = new WebClient();
            webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
            var uri = new Uri("http://www.sample.com/api/purchases", UriKind.Absolute);
            webClient.Headers[HttpRequestHeader.ContentLength] = postData.Length.ToString();
            webClient.AllowWriteStreamBuffering = true;
            webClient.Encoding = System.Text.Encoding.UTF8;
            webClient.UploadStringAsync(uri, "POST", postData.ToString());
            webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(postComplete);
            System.Threading.Thread.Sleep(200);
        }




  private void postComplete(object sender, UploadStringCompletedEventArgs e)
    {
        reset.Set();
        Response result = JsonConvert.DeserializeObject<Response>(e.Result);
        if (result.success == true)
        {
            DispatchCommandResult(new PluginResult(PluginResult.Status.OK, package_id));
        }
    }



回答2:


change the method to "GET" as I believe your not posting any data to a form



来源:https://stackoverflow.com/questions/14703087/http-post-get-response-error-for-windows-phone-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!