Search code examples
c#.netjsonwindows-phone-8webclient

Retrieve JSON string from URL in Windows Phone 8


I'm trying to get a Json string from an Url in a windows phone 8 application (the page requires an authentication and I think that's where my code is failing), I'm using the following code:

    public WebClient client = new WebClient();
    public string result;

    public void DoStuff()
    {
        string username = "username";
        string password = "password";
        string url = "myurl";
        client.Credentials = new NetworkCredential(username, password);
        client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
        client.DownloadStringAsync(new Uri(url));
    }
    void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        result = e.Result;
    }

However, when run the app, I got a System.Reflection.TargetInvocationException at e.result

Going into InnerException I see this:

[System.Net.WebException] {System.Net.WebException: An exception occurred during a WebClient request. ---> System.Net.ProtocolViolationException: A request with this method cannot have a request body. at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state) at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult) at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result) at System.Net.WebClient.DownloadBitsResponseCallback(IAsyncResult result) --- End of inner exception stack trace ---} System.Net.WebException

I've tried with HttpClient but I got the same problem. I would like to know if somebody knows how to solve this.

Thanks!

UPDATE: I've tried navigating to the page on my phone using IE, and then the IE Mobile says: "Unsupported Address, IE Mobile doesn't support this type of address and can't display this page". That's why the app is crashing too?


Solution

  • GET Method (with/without Credentials)

    private string username = "user";
    private string password = "passkey";
    private string myUrl = "http://some_url.com/id?=20";
    private WebClient client = new WebClient();
    
    private void retrieveJson()
    {
            client.Credentials = new NetworkCredential(username, password);
            client.Encoding = Encoding.UTF8;
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
            client.DownloadStringAsync(new Uri(myUrl), UriKind.Relative);
    }
    //WebClient String (json content) Download
    private void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
            // You will get you Json Data here..
            var myJSONData = e.Result;
            JObject JsonData = JObject.Parse(myJSONData);
            //Do something with json 
            //Ex: JsonData["Array1"][5]
    }
    

    POST Method (with/without Credentials)

    private string username = "user";
    private string password = "passkey";
    private string myUrl = "http://some_url.com/id?=20";
    private WebClient client = new WebClient();
    private string parameters = "{\"I_NAME\":\"0000"\"}"; //Example
    
    private void postMethod()
    {
            client.Credentials = new NetworkCredential(username, password);
            client.Encoding = Encoding.UTF8;
            client.Headers["Content-Length"] = parameters.Length.ToString();
            client.UploadStringCompleted += new UploadStringCompletedEventHandler(client_UploadStringCompleted);
    
            client.UploadStringAsync(new Uri(myUrl), "POST", parameters);
    }
    
    private void client_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
    {
            if (e.Error == null)
            {
                var myJSONData = e.Result;
                JObject JsonData = JObject.Parse(myJSONData);
            }
    }