在 Windows 8.1 中使用 WebView 发布
或者更好的是,使用WebView.NavigateWithHttpRequestMessage(HttpRequestMessage requestMessage)。
您可以使用Windows.Web.Http.HttpRequestMessage 来设置HTTP 方法和请求内容等。
例如:
HttpRequestMessage request = new HttpRequestMessage(
HttpMethod.Post,
new Uri("http://localhost"));
request.Content = new HttpStringContent(
String.Format("user_id={0}&session_id={1}", "Chinese", "food"));
webView.NavigateWithHttpRequestMessage(request);
这相当于以下 HTTP 请求:
POST / HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
Accept-Language: en-US,en;q=0.5
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; Touch; MASAJS; WebView/2.0; rv:11.0) like Gecko
Accept-Encoding: gzip, deflate
Host: localhost
Content-Length: 31
Connection: Keep-Alive
Cache-Control: no-cache
user_id=Chinese&session_id=food
在 Windows 8 中使用 WebView 发布
对于 Windows 8,请使用 JavaScript!
- 创建一个
<form>,将action 设置为您的目标URI,并将method 设置为POST。
- 添加两个
<input> 并用您想要的名称命名它们,在本例中为user_id 和session_id。
- 添加设置输入值并提交表单的脚本。
例如:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
webView.NavigateToString(@"<html>
<head>
<script type='text/javascript'>
function doSomething(userIdValue, sessionIdValue)
{
document.getElementById('user_id').value = userIdValue;
document.getElementById('session_id').value = sessionIdValue;
document.getElementById('myForm').submit();
return 'Hello World!';
}
</script>
</head>
<body>
<form id='myForm' action='http://localhost' method='post'>
<input type='hidden' id='user_id' name='user_id' />
<input type='hidden' id='session_id' name='session_id' />
</form>
</body>
</html>");
}
private void Button_Click(object sender, RoutedEventArgs e)
{
string result = webView.InvokeScript("doSomething", new string[] { "Chinese", "food" });
}
这将发送这样的请求:
POST / HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
Accept-Language: en-US,en;q=0.5
User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0; Touch; MASAJS; WebView/1.0)
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
Host: localhost
Content-Length: 31
Connection: Keep-Alive
Cache-Control: no-cache
user_id=Chinese&session_id=food