gpt4 book ai didi

javascript - 如何使用 webview 或 Web 浏览器在 android Studio 中显示 OKHTTP html 响应并与之交互

转载 作者:行者123 更新时间:2023-11-29 19:07:20 24 4
gpt4 key购买 nike

我正在构建一个 Android 应用程序。我已经使用 OKHTTP 构建了一个请求,我得到的响应是一个由 html css 和 js 内容组成的字符串。此响应实际上是用户必须使用的一种形式,以允许应用程序与给定网站进行通信。

现在我希望用户能够看到该响应作为 html 页面并单击按钮以允许通信。唯一的问题是我不知道如何在 WebView 或网络浏览器中将该响应显示为 html。

来自 MainActivity:

                          Authenticate myAouth = new Authenticate("myCostumerKey","mySecretKey");
try {
myResponse=myAouth.run("myUrlHere");
//System.out.println( myResponse);
} catch (Exception e) {
e.printStackTrace();
}

认证类

public class Authenticate {
private final OkHttpClient client;
String[] myResponse =new String[2];
public Authenticate( final String consumerKey, final String consumerSecret) {

client = new OkHttpClient.Builder()
.authenticator(new Authenticator() {
@Override public Request authenticate(Route route, Response response) throws IOException {
if (response.request().header("Authorization") != null) {
return null; // Give up, we've already attempted to authenticate.
}

System.out.println("Authenticating for response: " + response);
System.out.println("Challenges: " + response.challenges());
String credential = Credentials.basic(consumerKey, consumerSecret);
Request myRequest =response.request().newBuilder()
.header("Authorization", credential)
.build();
HttpUrl myURL = myRequest.url();
myResponse[0]= String.valueOf(myURL);
return myRequest;
}
})
.build();
}

@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public String[] run(String url) throws Exception {
Request request = new Request.Builder()
.url(url)
.build();


try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
myResponse[1]=response.body().string();
System.out.println(" URL is "+myResponse[0]+" my response body is "+myResponse[1]);

}

return myResponse;
}}

如有任何帮助,我们将不胜感激。

亲切的问候

最佳答案

您可以使用以下代码将String转换为HTML,然后将其显示在WebView中

    try {
String html = new String(response, "UTF-8");
String mime = "text/html";
String encoding = "utf-8";

myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.loadDataWithBaseURL(null, html, mime, encoding, null);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}

关于javascript - 如何使用 webview 或 Web 浏览器在 android Studio 中显示 OKHTTP html 响应并与之交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46690975/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com