0
我在WindowsPhone上打開WebResponse時出現問題,總是在我打開WebResponse時收到異常。我嘗試了很多不同的方法,但是當我使用異步方法時,總會得到一個異常。 請幫幫我。Xamarin-CrossPlatform POST HttpWebRequest:遠程服務器返回錯誤:NotFound
例外:
An exception of type 'System.Net.WebException' occurred in System.Net.ni.DLL but was not handled in user code Additional information: The remote server returned an error: 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手機上不可用!
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);
}