Skip to content

Instantly share code, notes, and snippets.

@rahulk11
Last active November 7, 2019 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rahulk11/dd9fa58bac561c69bff704a24db28747 to your computer and use it in GitHub Desktop.
Save rahulk11/dd9fa58bac561c69bff704a24db28747 to your computer and use it in GitHub Desktop.
A simple "java webview server" for handling intercepted WebView requests on Android and deliver local content. Translated into java from originally kotlin source - https://gist.github.com/ErikHellman/3d131596a8d6a10eb78c418a64281cf5
/*
MIT License
Copyright (c) 2019 Rahul Kumar
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package in.rahulkr.webviewserver;
import android.content.res.AssetManager;
import android.net.Uri;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Map;
class Request {
String url, method;
Map<String, String> headers;
public Request(String url, String method, Map<String, String> headers) {
this.url = url;
this.method = method;
this.headers = headers;
}
public static Request fromWebResourceRequest(WebResourceRequest webResourceRequest) {
return new Request(
webResourceRequest.getUrl().toString(),
webResourceRequest.getMethod(),
webResourceRequest.getRequestHeaders()
);
}
}
class Response {
int statusCode;
String reasonPhrase, mimeType, encoding;
Map<String, String> responseHeaders;
InputStream data;
public Response(int statusCode, String reasonPhrase, String mimeType,
String encoding, Map<String, String> responseHeaders, InputStream data) {
this.statusCode = statusCode;
this.reasonPhrase = reasonPhrase;
this.mimeType = mimeType;
this.encoding = encoding;
this.responseHeaders = responseHeaders;
this.data = data;
}
public WebResourceResponse toWebResourceResponse() {
return new WebResourceResponse(
mimeType, encoding, statusCode, reasonPhrase, responseHeaders, data
);
}
}
interface RequestHandler {
public boolean shouldHandleRequest(Request request);
public Response handleRequest(Request request);
}
/**
* This class will act as a web server for intercepted request from a `WebView`. Simply implement your own
* `WebViewClientCompat` and assign it as the `webViewClient` of your `WebView` and call `handleWebViewRequest()` from
* `WebViewClient.shouldInterceptRequest()`.
* <p>
* Just add your own `RequestHandler` for every response you want to return. Two ready-made implementations
* of `RequestHandler` are provided: `FileRequestHandler` and `AssetRequestHandler`. See respective class for details.
* <p>
* If no matching `RequestHandler` is found, a default 404 response will be returned.
*/
public class WebViewServer {
static Response NOT_FOUND_RESPONSE = new Response(
404, "Not found", "text/plain",
"UTF-8",
null, null
);
private ArrayList<RequestHandler> requestHandlers = new ArrayList<>();
public void addRequestHandler(RequestHandler requestHandler) {
requestHandlers.add(requestHandler);
}
public WebResourceResponse handleWebViewRequest(WebResourceRequest webResourceRequest) {
Request request = Request.fromWebResourceRequest(webResourceRequest);
for (RequestHandler requestHandler : requestHandlers) {
if (requestHandler.shouldHandleRequest(request)) {
return requestHandler.handleRequest(request).toWebResourceResponse();
}
}
return NOT_FOUND_RESPONSE.toWebResourceResponse();
}
}
/**
* Returns a response containing the content of the specified `File`. Note that the content of the file
* is cached in memory, so beware of loading too large files using this class. For very large files,
* please provide your own `RequestHandler` that streams the content to the `WebView` instead.
*/
class FileRequestHandler implements RequestHandler {
private File file;
private String requestPath, mimeType, encoding;
private byte[] bytes;
public FileRequestHandler(File file, String requestPath,
String mimeType, String encoding) {
this.file = file;
this.requestPath = requestPath;
this.mimeType = mimeType;
this.encoding = encoding;
init();
}
public void init() {
try {
int size = (int) file.length();
bytes = new byte[size];
FileInputStream fis = new FileInputStream(file);
fis.read(bytes);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public boolean shouldHandleRequest(Request request) {
Uri uri = Uri.parse(request.url);
return uri.getPath().equals(requestPath);
}
@Override
public Response handleRequest(Request request) {
return new Response(200, "OK", mimeType, encoding,
null, new ByteArrayInputStream(bytes));
}
}
/**
* Returns a response containing the content of the specified Android asset. Note that the content of the file
* is cached in memory, so beware of loading too large files using this class. For very large files,
* please provide your own `RequestHandler` that streams the content to the `WebView` instead.
*/
class AssetRequestHandler implements RequestHandler {
AssetManager assetManager;
String assetPath, requestPath, mimeType, encoding;
byte[] bytes;
public AssetRequestHandler(AssetManager assetManager, String assetPath, String requestPath,
String mimeType, String encoding) {
this.assetManager = assetManager;
this.assetPath = assetPath;
this.requestPath = requestPath;
this.mimeType = mimeType;
this.encoding = encoding;
init();
}
public void init() {
try {
InputStream is = assetManager.open(assetPath);
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
bytes = output.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public boolean shouldHandleRequest(Request request) {
Uri uri = Uri.parse(request.url);
return uri.getPath().equals(requestPath);
}
@Override
public Response handleRequest(Request request) {
return new Response(200, "OK", mimeType,
encoding, null, new ByteArrayInputStream(bytes));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment