c# - Cant get Async (async await) download of JSON to work -
i've been struggling while now, can't work. i'm trying download json string windows phone 8 application, using 'sort of' async await.
i'm using the promising solution of matthias shapiro.
httpextensions.cs
public static class httpextensions { public static task<stream> getrequeststreamasync(this httpwebrequest request) { var taskcomplete = new taskcompletionsource<stream>(); request.begingetrequeststream(ar => { stream requeststream = request.endgetrequeststream(ar); taskcomplete.trysetresult(requeststream); }, request); return taskcomplete.task; } public static task<httpwebresponse> getresponseasync(this httpwebrequest request) { var taskcomplete = new taskcompletionsource<httpwebresponse>(); request.begingetresponse(asyncresponse => { try { httpwebrequest responserequest = (httpwebrequest)asyncresponse.asyncstate; httpwebresponse someresponse = (httpwebresponse)responserequest.endgetresponse(asyncresponse); taskcomplete.trysetresult(someresponse); } catch (webexception webexc) { httpwebresponse failedresponse = (httpwebresponse)webexc.response; taskcomplete.trysetresult(failedresponse); } }, request); return taskcomplete.task; } } public static class httpmethod { public static string head { { return "head"; } } public static string post { { return "post"; } } public static string put { { return "put"; } } public static string { { return "get"; } } public static string delete { { return "delete"; } } public static string trace { { return "trace"; } } public static string options { { return "options"; } } public static string connect { { return "connect"; } } public static string patch { { return "patch"; } } }
and mainpageviewmodel.cs
protected override void onactivate() { base.onactivate(); getsessions(); } private async void getsessions() { var result = await getmydata("http://localhost/api/mydata"); } public async task<string> getmydata(string urltocall) { httpwebrequest request = (httpwebrequest)webrequest.create(urltocall); request.method = httpmethod.get; httpwebresponse response = (httpwebresponse)await request.getresponseasync(); using (var sr = new streamreader(response.getresponsestream())) { return sr.readtoend(); } }
once hits "httpwebresponse someresponse = (httpwebresponse)responserequest.endgetresponse(asyncresponse);", i'm getting webexception:
"system.net.webexception: remote server returned error: notfound"
when dive bit deeper, notice error isn't actual error. when check "asyncresponse" inside getresponseasync method in httpextensions class notice error:
"asyncwaithandle = 'asyncresponse.asyncwaithandle' threw exception of type 'system.notsupportedexception'"
i have no idea how work. i'm doing wrong?
i see problem now. since emulator using virtual machine cannot use localhost because localhost phone , not pc. see solution: windows phone 8 emulator: access localhost
Comments
Post a Comment