get json from webservices with webclient without manipulate data in other method - c#

I'm developping on Windows phone 8 and I would like to know if it's possible to manipulate data in the same method when we call DownloadStringCompleted of WebClient?
private void DownloadDataFromWebService(String uri)
{
WebClient wc = new WebClient();
wc.DownloadStringAsync(new Uri(uri));
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
}
private void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
RootObject r = JsonConvert.DeserializeObject<RootObject>(e.Result);
List<Category> listeCategories = r.Result;
}
Thus, I would like to manage all code in only one method because I would like to return an object
For example,
private List<Category> GetCategories(String uri)
{
WebClient wc = new WebClient();
wc.DownloadStringAsync(new Uri(uri));
.....
.....
RootObject r = JsonConvert.DeserializeObject<RootObject>(e.Result);
return (List<Category>) r.Result;
}

Yes, that is possible, due to magic TaskCompletionSource class, http://msdn.microsoft.com/en-us/library/dd449174(v=vs.95).aspx . To download:
async Task<List<object>> getCategories(String uri)
{
var taskCompletionObj = new TaskCompletionSource<string>();
var wc= new webClient();
wc.DownloadStringAsync(new URI(uri, Urikind.Absolute)) += (o, e) =>
{
taskCompletionObj.TrySetResult(e.Result);
};
string rawString = await taskCompletionObj.Task;
RootObject r = JsonConvert.DeserializeObject<RootObject>(rawString);
return (List<Category>)r.Result;
}
To use: var x = await getCategories(myURI);

Related

await WebClient.DownloadFileTaskAsync not working

I'm trying to use WebClient.DownloadFileTaskAsync to download a file so that I can make use of the download progress event handlers. The problem is that even though I'm using await on DownloadFileTaskAsync, it's not actually waiting for the task to finish and exits instantly with a 0 byte file. What am I doing wrong?
internal static class Program
{
private static void Main()
{
Download("http://ovh.net/files/1Gb.dat", "test.out");
}
private async static void Download(string url, string filePath)
{
using (var webClient = new WebClient())
{
IWebProxy webProxy = WebRequest.DefaultWebProxy;
webProxy.Credentials = CredentialCache.DefaultCredentials;
webClient.Proxy = webProxy;
webClient.DownloadProgressChanged += (s, e) => Console.Write($"{e.ProgressPercentage}%");
webClient.DownloadFileCompleted += (s, e) => Console.WriteLine();
await webClient.DownloadFileTaskAsync(new Uri(url), filePath).ConfigureAwait(false);
}
}
}
As others have pointed, The two methods shown are either not asynchronous or not awaitable.
First, you need to make your download method awaitable:
private async static Task DownloadAsync(string url, string filePath)
{
using (var webClient = new WebClient())
{
IWebProxy webProxy = WebRequest.DefaultWebProxy;
webProxy.Credentials = CredentialCache.DefaultCredentials;
webClient.Proxy = webProxy;
webClient.DownloadProgressChanged += (s, e) => Console.Write($"{e.ProgressPercentage}%");
webClient.DownloadFileCompleted += (s, e) => Console.WriteLine();
await webClient.DownloadFileTaskAsync(new Uri(url), filePath).ConfigureAwait(false);
}
}
Then, you either wait on Main:
private static void Main()
{
DownloadAsync("http://ovh.net/files/1Gb.dat", "test.out").Wait();
}
Or, make it asynchronous, too:
private static async Task Main()
{
await DownloadAsync("http://ovh.net/files/1Gb.dat", "test.out");
}

post request in windows phone 8.1

I want to do this thing in windows phone 8.1 please suggest how to do.I have tried httpclient but didn't achieve the same result please suggest me something
private async void Button_Click(object sender, RoutedEventArgs e)
{
WebClient web = new WebClient();
web.Headers["content-type"] = "application/x-www-form-urlencoded";
string arg = "id=" + newone.Text;
// var postdata =js
string arg1 = "id=" + newone.Text;
//web.UploadStringAsync(new Uri("http://terasol.in/hoo/test.php/?id=&ncuavfvlqfd"), "GET");
web.UploadStringAsync(new Uri("http://terasol.in/hoo/test.php"), "POST", arg1);
web.UploadStringCompleted += web_uploadstringcomplete;
}
void web_uploadstringcomplete(object sender, UploadStringCompletedEventArgs e)
{
MessageBox.Show(e.Result);
}
thank you
Based on your sample code, and running it,
using the following code, I get the same value returned.
private static void Button_Click2(string id)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://terasol.in/");
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("id", id)
});
var result = client.PostAsync("/hoo/test.php", content).Result;
string resultContent = result.Content.ReadAsStringAsync().Result;
Console.WriteLine(resultContent);
}
}

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?
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);
}
}

Retrieving data from secure website on Windows Phone 8

I am trying to retrieve data from an authorization-restricted database which only contains text to my Windows Phone 8 app. My code looks like this:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
WebClient wc = new WebClient();
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
wc.Credentials = new NetworkCredential("username", "password");
wc.DownloadStringAsync(new Uri(#"http://www.siteaddress.com"));
}
void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
string text = e.Result;
}
Unfortunately I'm getting the following message. Am I doing anything wrong? Thanks in advance.
http://s30.postimg.org/yuc0mcb5t/pic.png
If you are trying to send data to the server to receive response from the server, then you mean POST data to server .
void GetPosts(string UserID)
{
WebClient webclient = new WebClient();
Uri uristring = new Uri("somelink.com");
webclient.Headers["Content-Type"] = "application/x-www-form-urlencoded";
string postJsonData = string.Empty;
postJsonData += "userId=" + UserID;//parameters you want to POST
webclient.UploadStringAsync(uristring, "POST", postJsonData);
webclient.UploadStringCompleted += webclient_UploadStringCompleted;
}
void webclient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
.... // any code
}

How can i download a website content to a string?

I tried this and i want that the source content of the website will be download to a string:
public partial class Form1 : Form
{
WebClient client;
string url;
string[] Search(string SearchParameter);
public Form1()
{
InitializeComponent();
url = "http://chatroll.com/rotternet";
client = new WebClient();
webBrowser1.Navigate("http://chatroll.com/rotternet");
}
private void Form1_Load(object sender, EventArgs e)
{
}
static void DownloadDataCompleted(object sender,
DownloadDataCompletedEventArgs e)
{
}
public string SearchForText(string SearchParameter)
{
client.DownloadDataCompleted += DownloadDataCompleted;
client.DownloadDataAsync(new Uri(url));
return SearchParameter;
}
I want to use WebClient and downloaddataasync and in the end to have the website source content in a string.
No need for async, really:
var result = new System.Net.WebClient().DownloadString(url)
If you don't want to block your UI, you can put the above in a BackgroundWorker. The reason I suggest this rather than the Async methods is because it is dramatically simpler to use, and because I suspect you are just going to stick this string into the UI somewhere anyway (where BackgroundWorker will make your life easier).
If you are using .Net 4.5,
public async void Downloader()
{
using (WebClient wc = new WebClient())
{
string page = await wc.DownloadStringTaskAsync("http://chatroll.com/rotternet");
}
}
For 3.5 or 4.0
public void Downloader()
{
using (WebClient wc = new WebClient())
{
wc.DownloadStringCompleted += (s, e) =>
{
string page = e.Result;
};
wc.DownloadStringAsync(new Uri("http://chatroll.com/rotternet"));
}
}
Using WebRequest:
WebRequest request = WebRequest.Create(url);
request.Method = "GET";
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string content = reader.ReadToEnd();
reader.Close();
response.Close();
You can easily call the code from within another thread, or use background worer - that will make your UI responsive while retrieving data.

Categories