WebClient not found in mobile development in c#

Rahul Kiwitech
Rahul K...
292 Points
26 Posts

Hi,

I am try to call JSON API in windows phone 8.1 in VS 2015. I am using WebClient to call but getting compile time error "C# The type or namespace name 'WebClient' could not be found (are you missing a using directive or an assembly reference?)".

I am try to implement following code:

public void CallPostAPI() {
WebClient wc = new WebClient();
var URI = new Uri("https://your_uri_goes_here");
wc.Headers["Content-Type"] = "application/json";
wc.UploadStringCompleted += new UploadStringCompletedEventHandler(CallPostAPICompleted);
wc.UploadStringAsync(URI, "POST", "Data_To_Be_sent");
}
void CallPostAPICompleted(object sender, UploadStringCompletedEventArgs e) {
try {
var result = e.Result;
} catch (Exception exc) {
//
}
}

 

Thanks in advance.

Views: 10232
Total Answered: 2
Total Marked As Answer: 0
Posted On: 05-Jun-2016 05:26

Share:   fb twitter linkedin
Answers
NiceOne Team
NiceOne...
1390 Points
18 Posts
         

Hey Rahul,

It's sound like you are building windows app store application for windows phone 8.1. In this case use HttpClient instead of WebClient. WebClient is available for Windows Phone Silverlight 8.1 apps. Windows Phone Runtime apps use Windows.Web.Http.HttpClient.

see the  following code snippet that call a json auth post api as :

public static async Task<string> AuthenticateUserAsync(string UserID, string Password) {
using (var client = new HttpClient()) {
client.BaseAddress = new Uri("https://www.exaple.com/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response;
// HTTP POST
response = await client.PostAsync("api/Auth", new StringContent("[\""+ UserID + "\",\"" + Password + "\"]", Encoding.UTF8, "application/json") );
if (response.IsSuccessStatusCode) {
return response.Content.ReadAsStringAsync().Result;
} else {
return response.StatusCode.ToString();
}
}
}

  

Posted On: 05-Jun-2016 05:48
Priya
Priya
1194 Points
33 Posts
         

I found other example that use HttpClient and uses encoding to post data.

using System;
using System.Collections.Generic;
using System.Net.Http;
class Program {
static void Main() {
using (var client = new HttpClient()) {
client.BaseAddress = new Uri("https://localhost:6740");
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("", "login")
});
var result = client.PostAsync("/api/Membership/exists", content).Result;
string resultContent = result.Content.ReadAsStringAsync().Result;
Console.WriteLine(resultContent);
}
}
}

 

Posted On: 05-Jun-2016 06:01
 Log In to Chat