【发布时间】:2016-09-06 22:23:52
【问题描述】:
我在 WindowsPhone 上打开 WebResponse 时遇到问题,当我打开 WebResponse 时总是出现异常。我尝试了许多不同的方法,但是当我使用异步方法时总是会出现异常。 请帮帮我。
例外:
System.Net.ni.DLL 中出现“System.Net.WebException”类型的异常,但未在用户代码中处理 附加信息:远程服务器返回错误:NotFound。
private async void btLogin_Click(object sender, RoutedEventArgs e) {
Uri uri = new Uri("http://ip-address/users/User/jan_kowalski/a");
HttpWebRequest webRequest = WebRequest.Create(uri) as HttpWebRequest;
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
try {
using (Stream ss = await webRequest.GetRequestStreamAsync()) {
await ss.WriteAsync(new byte[0], 0, 0);
await ss.FlushAsync();
}
//using (WebResponse webResponse = await webRequest.GetResponseAsync()) { // <-- Here there is an exception or...
// using (StreamReader reader = new StreamReader(webResponse.GetResponseStream())) {
// string data = await reader.ReadToEndAsync();
// Log.d(TAG, data);
// }
//}
webRequest.BeginGetResponse(async (x) => {
WebResponse webResponse = webRequest.EndGetResponse(x); // <-- ...or here there is an exception
StreamReader reader = new StreamReader(webResponse.GetResponseStream());
string text = await reader.ReadToEndAsync();
Log.d(TAG, text);
}, null);
} catch (WebException exc) {
Log.e(TAG, exc.Message + " \n" +
exc.Source + "\n status:" +
exc.Status + "\n" +
exc.Response + " \n " +
exc.StackTrace);
} catch (Exception ex) {
Log.e(TAG, ex.Message + "\n stackTrace: " + ex.StackTrace);
}
}
我注意到 Android 和 IOS 可以访问更多的方法,同步方法。当他们使用它一切正常时,我从服务器得到正确的答案。但同步方法在 Windows phone 上不可用!
Uri uri = new Uri("http://ip-address/users/User/jan_kowalski/a");
WebRequest webRequest = WebRequest.Create(uri);
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
try {
using (Stream stream = webRequest.GetRequestStream()) {
stream.Write(new byte[0], 0, 0);
}
using (WebResponse stream = webRequest.GetResponse()) {
using (StreamReader reader = new StreamReader(stream.GetResponseStream())) {
string data = reader.ReadToEnd();
Console.WriteLine(data);
}
}
}catch(Exception ex) {
Log.e(TAG, null, ex);
}
【问题讨论】:
标签: c# xamarin httpwebrequest