要从运行中的服务获取网站URL,可以使用以下解决方法:
WebView
加载网页,并获取当前加载的URL:WebView webView = new WebView(getApplicationContext());
webView.loadUrl("https://example.com");
String currentUrl = webView.getUrl();
HttpURLConnection
发送HTTP请求获取网页内容,并从响应头中获取URL:URL url = new URL("https://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
String currentUrl = connection.getURL().toString();
}
OkHttp
库发送HTTP请求获取网页内容,并从响应头中获取URL:首先,在build.gradle
文件中添加以下依赖项:
implementation 'com.squareup.okhttp3:okhttp:4.9.1'
然后,在服务中使用以下代码获取URL:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://example.com")
.build();
try (Response response = client.newCall(request).execute()) {
if (response.isSuccessful()) {
String currentUrl = response.request().url().toString();
}
}
无论使用哪种方法,都需要在服务中使用网络权限。在AndroidManifest.xml
文件中添加以下权限: