Xamarin 中的 Webview 状态代码 Android

Webview Status Code in Xamarin Android

我检查了以下 java resource to get the status code of Webview for Xamarin Android from c#. As from Xamarin documentation WebResourceResponse(String, String, Stream) 流 api 的类型为 System.IO.Stream。我需要将 Java.IO.InputStream 转换为 System.IO.Stream

是否可以转换这些类型?。如果不是,可能的解决方法是什么。我是 Xamarin 的新手。请帮忙。

private static string http = "https?://[\w\.\-]+(/.*)?";
Regex regex = new Regex(http);

public override WebResourceResponse ShouldInterceptRequest(WebView webView, string url)
{
    if (!regex.IsMatch(http))
    {
        return ShouldInterceptRequest(webView, url);
    }

    HttpGet req= new HttpGet(url);
    DefaultHttpClient client = new DefaultHttpClient();

    String mimetype = null, encoding = null;

    byte[] data = null;

    try
    {
        var response = client.Execute(req); 

        if (HttpStatus.ScOk == response.StatusLine.StatusCode)
        {
            var httpentity = response.Entity;
            var header = httpentity.ContentType;

            if (null != mimetype) mimetype = header.Value;

            var encodingheader = httpentity.ContentEncoding;
            if (null != encodingheader) encoding = encodingheader.Value;

            data = EntityUtils.ToByteArray(httpentity);
        }
    }
    catch (Exception e)
    {
        String msg = e.Message;
        Log.Error(this.Class.SimpleName, (null != msg) ? msg : "");
    }
    finally
    {
        req.Abort();
        client.ConnectionManager.Shutdown();
    }

    Java.IO.InputStream stream = new ByteArrayInputStream(data);

    // this is the error i get
    // cannot convert from 'Java.IO.InputStream' to 'System.IO.Stream'
    // Argument type 'Java.IO.InputStream' is not assignable to parameter type 'System.IO.Stream'
    return new WebResourceResponse(mimetype, encoding, stream);

}

Is it possible convert these type?

答案是否定的,不能直接转换,可以使用文件来实现,但会使问题复杂化。

在您的问题中,您可以使用 MemoryStream class,它可以在其构造中接受 Byte[] 作为参数。

替换

Java.IO.InputStream stream = new ByteArrayInputStream(data);

与:

MemoryStream stream = new MemoryStream(data);