发送请求&在Windows Phone 8.1 WinRT中获取响应

时间:2016-02-04 04:54:18

标签: c# .net windows-runtime windows-phone-8.1

我已从Windows Phone 8 Silverlight迁移到Windows Phone 8.1 WinRT。 WP 8 Silverlight中使用的HttpWebRquestWebClient。 Wp 8.0 silverlight,我使用过webclient ..

 webClntRech.DownloadStringAsync(new Uri("http://wallet.net.co.in/services/bi/rechargedownload/01/0001/" + DateTime.Now.ToString("ddMMyyhhmmssms") + "/504434"));

            webClntRech.DownloadStringCompleted += webClntRech_DownloadStringCompleted;

我想要WInrt 8.1中的类似功能

我在WinRT中找不到WebClient。我遇到了HttpClient

根据要求,我们必须为所有请求实现POST方法。我按照一些例子得到了这个代码..它不起作用..

 HttpClient client = new HttpClient();
        string ResponceResult = await client.PostAsync("http://wallet.net.co.in/services/bi/rechargedownload/01/0001/" + DateTime.Now.ToString("ddMMyyhhmmssms") + "/504434",);

 MessageDialog m = new MessageDialog(ResponceResult);
        await m.ShowAsync();

响应将采用Json格式。

我不熟悉PostAynsc()方法的HTTP内容参数。

经历了几个链接。无法得到任何帮助。 如何实现..

3 个答案:

答案 0 :(得分:1)

首先,您需要更改您的网址,即:http://services.groupkt.com/country/get/all

然后尝试这个

sending an Http request to rest api on Windows Phone 8.1

我希望这对你有所帮助

答案 1 :(得分:0)

我使用此实用程序方法来POST JSON

 async void PostJson(string URL, string json)
 {
     HttpClient httpClient = new HttpClient();
     httpClient.Timeout = TimeSpan.FromMinutes(5);
     httpClient.MaxResponseContentBufferSize = 25600000;

     httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
     httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "application/json");

     HttpResponseMessage response = await httpClient.PostAsync(new Uri(URL), new StringContent(json, Encoding.UTF8, "application/json"));
     response.EnsureSuccessStatusCode();
     string responseAsText = await response.Content.ReadAsStringAsync();
     Dictionary<string, string> responseJson = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseAsText);
 }

<强>更新

为了从URL获取JSON,您可以使用以下代码:

var httpClient = new HttpClient();
var response = await httpClient.GetStringAsync(url);

// Deserialize JSON
MyObject myObject = JsonConvert.DeserializeObject<MyObject>(response);

答案 2 :(得分:0)

我在HttpClient

中使用了类似的内容
public async Task<string> httpClient(object param, Uri targetUri, string key)
    {
        using(HttpClient client = new HttpClient())
        {
            string jsonData = JsonConvert.SerializeObject(param);
            FormUrlEncodedContent content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>(key, jsonData)
            });
            HttpResponseMessage response = await client.PostAsync(targetUri, content);
            string result = await response.Content.ReadAsStringAsync();
            return result;
        }
    }

你可以任何你想要的方式修改它

我使用Task而不是void,所以我可以等待结果,然后我在另一种方法中反序列化