我有一个简单的Xamarin.Forms页面,其中包含WebView,运行良好。 现在我想为URL调用POST-Requests(发送表单数据)。 我是否必须为Android,iOS和UWP创建3个不同的视图才能实现这一点 - 或者是否有办法在我的Xamarin-Forms项目的共享编码中只实现一次C#post-request代码?
答案 0 :(得分:1)
正如@ hvaughan3所说,你可以像这样使用HttpClient(来自你的Xamarin Forms项目的共享代码):
private static HttpClient client = new HttpClient() { Timeout = TimeSpan.FromSeconds(30) };
HttpContent content = new StringContent(JsonConvert.SerializeObject(objectToPost), Encoding.UTF8, "application/x-www-form-urlencoded");
var response = await client.PostAsync(new Uri("http://your.url"), content);
if (response.IsSuccessStatusCode) {
var responseFromServer = await response.Content.ReadAsStringAsync();
}
else {
// handle errors
}
答案 1 :(得分:0)
使用HTTPcLient进行form-URLencoded post请求,然后创建自定义Webview来处理cookie。使用由seansparkman创建的CookieWebView Nuget包。
答案 2 :(得分:0)
通过网络视图发布请求 对于WkWebview
[assembly: ExportRenderer(typeof(PaymentWebview), typeof(PaymentWebViewRenderer))]
namespace MMFInvestorApp.iOS.Utils
{
public class PaymentWebViewRenderer : WkWebViewRenderer
{
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
if (NativeView != null)
{
var request = new NSMutableUrlRequest(new NSUrl(new NSString(paymentwebview.url))); //Your Url
request.HttpMethod = "POST";
request.Body = NSData.FromString(paymentwebview.data); //Data for POST
request["Content-Length"] = req.Body.Length.ToString();
request["Content-Type"] = "application/x-www-form-urlencoded charset=utf-8";
LoadRequest(request);
}
}
}
}
用于UIWebview(自2020年4月起废弃
[assembly: ExportRenderer(typeof(PaymentWebview), typeof(PaymentWebViewRenderer))]
namespace MMFInvestorApp.iOS.Utils
{
public class PaymentWebViewRenderer : WebViewRenderer
{
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
if (NativeView != null)
{
var paymentwebview = Element as PaymentWebview;
var request = new NSMutableUrlRequest(new NSUrl(new NSString(paymentwebview.url)));//Your Url
request.Body = paymentwebview.data; //Data for POST
request.HttpMethod = "POST";
LoadRequest(request);
}
}
}
}