简体   繁体   中英

converting the http request to use webclient

I'm developing windows phone 8 application..
i cannot use the dll using system.net.httpwebrequest;
in windows phone 8, so i need to converet the http request to webclient can any one suggest how to convert it..?

     private HttpWebResponse GetHttpWebResponse(HttpWebRequest webRequest)
                {
                    HttpWebResponse response;

                    try
                    {
                        response = (HttpWebResponse)webRequest.GetResponse();
    //GetResponse() produce error that System.Net.HttpRequest dll is missing, 
    //so im in need to conertr the http request to webclient.
                    }
                    catch (WebException we)
                    {
                        response = (HttpWebResponse)we.Response;
                    }

                    return response;
                }

my complete Json data

    [
      {
        "id": 01,
        "address": "12asdf",
        "city": " chennai",
        "contact1": "",
        "contact2": "",
        "country": " india",
        "description": "",
        "name": " david",
        "region": "",
        "state": "  033",
        "website": "",
        "image": "",
         "PrayerTime": {
          "id": 01,
          "PrayerTime1": "00:52",
          "PrayerTime2": "21:04",
          "PrayerTime3": "12:27",
          "PrayerTime4": "05:35",
          "PrayerTime5": "21:04",
          "created_at": null,
          "PrayerTime6": "04:01",
          "updated_at": null,
          "organization_id": 001
        }
      },.............
      }

I recommend that you use the HttpClient instead (nuget package), it's more convenient and is supported also on WinRT.

Here is an example from trying to fetch geo coded data from social medias (which is irrelevant itself, but its a real world example :) , using HttpClient

(you need Newtonsoft.Json to use JObject/JArray)

You can probably waive the part where I add the DefaultRequestHeaders in your own call

            using (HttpClient client = new HttpClient())
            {
                string url = mediaConfig.RequestUrl + String.Format(mediaConfig.GeoCodeStringFormat, lat, lon, distance);

                if (mediaConfig.MediaName == "Twitter")
                    client.DefaultRequestHeaders.Add(mediaConfig.BearerTokenParamName, mediaConfig.BearerToken);
                else if (mediaConfig.MediaName == "Instagram")
                    url = url + "&" + mediaConfig.BearerTokenParamName + "=" + mediaConfig.BearerToken;
                else if (mediaConfig.MediaName == "GooglePlaces")
                    url = url + "&" + mediaConfig.BearerTokenParamName + "=" + mediaConfig.BearerToken;
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));

                response = await client.GetAsync(url);

                response.EnsureSuccessStatusCode();
            }
            responseString = await response.Content.ReadAsStringAsync();

Make sure your method signature has the async keyword, if you would to return "responseString":

    public async Task<string> methodname(... params ...

to "consume" this method from a sync method:

var mytask = methodname();
    mytask.ContinueWith(c =>
    {
         var jsonResponse = JObject.Parse(c.Result);
         // or JArray
         var jsonResponseArray = JArray.Parse(c.Result);

         foreach (var item in jsonResponseArray)
         {
              var id = item.SelectToken("id").ToString();
              // and so on...

         }
         var selectSomething = jsonResponse.SelectToken("somethinghere");
         Deployment.Current.Dispatcher.BeginInvoke(() =>
         {
                 // do your ui tasks, navigate etc...
         });
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM