Skip to content
This repository was archived by the owner on Feb 22, 2023. It is now read-only.

[webview_flutter] Webiew post url support #1970

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,15 @@
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.platform.PlatformView;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.List;
import java.util.Map;

public class FlutterWebView implements PlatformView, MethodCallHandler {
private static final String JS_CHANNEL_NAMES_FIELD = "javascriptChannelNames";
private static final String TAG = "FlutterWebView";
private final InputAwareWebView webView;
private final MethodChannel methodChannel;
private final FlutterWebViewClient flutterWebViewClient;
Expand Down Expand Up @@ -121,6 +124,9 @@ public void onMethodCall(MethodCall methodCall, Result result) {
case "loadUrl":
loadUrl(methodCall, result);
break;
case "postUrl":
postUrl(methodCall, result);
break;
case "updateSettings":
updateSettings(methodCall, result);
break;
Expand Down Expand Up @@ -162,6 +168,20 @@ public void onMethodCall(MethodCall methodCall, Result result) {
}
}

private static String initialParametersToString(Map<String, Object> parameters)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Expecting a Map -> application/x-www-form-urlencoded encoding in each platform implementation sounds a little fragile in case these implementations don't exactly match.

My preference would be to take a similar approach to Android's WebView and WkWebView where the encoding is the responsibility of the app developer, which allows some more flexibility for developers.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is how you're suppose to do that, webview send form by post with this.

throws UnsupportedEncodingException {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, Object> entry : parameters.entrySet()) {
sb.append(
URLEncoder.encode(entry.getKey(), "UTF-8")
+ "="
+ URLEncoder.encode(entry.getValue().toString(), "UTF-8")
+ "&");
}

return sb.deleteCharAt(sb.length() - 1).toString();
}

@SuppressWarnings("unchecked")
private void loadUrl(MethodCall methodCall, Result result) {
Map<String, Object> request = (Map<String, Object>) methodCall.arguments;
Expand All @@ -174,6 +194,18 @@ private void loadUrl(MethodCall methodCall, Result result) {
result.success(null);
}

@SuppressWarnings("unchecked")
private void postUrl(MethodCall methodCall, Result result) {
Map<String, Object> request = (Map<String, Object>) methodCall.arguments;
String url = (String) request.get("url");

byte[] params = (byte[]) request.get("params");

webView.postUrl(url, params);

result.success(null);
}

private void canGoBack(Result result) {
result.success(webView.canGoBack());
}
Expand Down
26 changes: 26 additions & 0 deletions packages/webview_flutter/ios/Classes/FlutterWebView.m
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// found in the LICENSE file.

#import "FlutterWebView.h"
#import <os/log.h>
#import "FLTWKNavigationDelegate.h"
#import "JavaScriptChannelHandler.h"

Expand Down Expand Up @@ -98,6 +99,8 @@ - (void)onMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
[self onUpdateSettings:call result:result];
} else if ([[call method] isEqualToString:@"loadUrl"]) {
[self onLoadUrl:call result:result];
} else if ([[call method] isEqualToString:@"postUrl"]) {
[self postUrl:call result:result];
} else if ([[call method] isEqualToString:@"canGoBack"]) {
[self onCanGoBack:call result:result];
} else if ([[call method] isEqualToString:@"canGoForward"]) {
Expand Down Expand Up @@ -340,6 +343,29 @@ - (bool)loadUrl:(NSString*)url withHeaders:(NSDictionary<NSString*, NSString*>*)
return true;
}

- (bool)postUrl:(FlutterMethodCall*)call result:(FlutterResult)result {
NSDictionary<NSString*, NSObject*>* args = [call arguments];

NSString* url = (NSString*)args[@"url"];
NSURL* nsUrl = [NSURL URLWithString:url];
if (!nsUrl) {
return false;
}

NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:nsUrl];
FlutterStandardTypedData* postData = (FlutterStandardTypedData*)args[@"params"];
NSString* contentLength = @(postData.data.length).stringValue;

[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData.data];

[request setValue:contentLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like the Android webview forces this encoding, do you know if multipart/form-data is allowed with WkWebView?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't know if you can send multipart like that, but code I've seen uses form encoded only


[_webView loadRequest:request];
return true;
}

- (void)registerJavaScriptChannels:(NSSet*)channelNames
controller:(WKUserContentController*)userContentController {
for (NSString* channelName in channelNames) {
Expand Down
13 changes: 13 additions & 0 deletions packages/webview_flutter/lib/platform_interface.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// found in the LICENSE file.

import 'dart:async';
import 'dart:typed_data';

import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
Expand Down Expand Up @@ -61,6 +62,18 @@ abstract class WebViewPlatformController {
"WebView loadUrl is not implemented on the current platform");
}

/// Post to the specified URL.
///
/// `url` must not be null
/// `params` must not be null
///
/// `params` have to be ascii encoded
/// Throws an ArgumentError if `url` is not a valid URL string.
Future<void> postUrl(String url, Uint8List params) {
throw UnimplementedError(
"Webview postUrl is not implemented on the current platform");
}

/// Updates the webview settings.
///
/// Any non null field in `settings` will be set as the new setting value.
Expand Down
11 changes: 11 additions & 0 deletions packages/webview_flutter/lib/src/webview_method_channel.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// found in the LICENSE file.

import 'dart:async';
import 'dart:typed_data';

import 'package:flutter/services.dart';

Expand Down Expand Up @@ -55,6 +56,16 @@ class MethodChannelWebViewPlatform implements WebViewPlatformController {
});
}

@override
Future<void> postUrl(String url, Uint8List params) async {
assert(url != null);
assert(params != null);
return _channel.invokeMethod('postUrl', <String, dynamic>{
'url': url,
'params': params,
});
}

@override
Future<String> currentUrl() => _channel.invokeMethod<String>('currentUrl');

Expand Down
14 changes: 14 additions & 0 deletions packages/webview_flutter/lib/webview_flutter.dart
Original file line number Diff line number Diff line change
Expand Up @@ -505,6 +505,20 @@ class WebViewController {
return _webViewPlatformController.loadUrl(url, headers);
}

/// Post to the specified URL.
///
/// `url` must not be null
/// `params` must not be null
///
/// `params` have to be ascii encoded
/// Throws an ArgumentError if `url` is not a valid URL string.
Future<void> postUrl(String url, List<int> params) async {
assert(url != null);
assert(params != null);
_validateUrlString(url);
return _webViewPlatformController.postUrl(url, params);
}

/// Accessor to the current URL that the WebView is displaying.
///
/// If [WebView.initialUrl] was never specified, returns `null`.
Expand Down