在Windowsapp store应用WebView中使用请求发布数据 – 使用C#

我的应用程序中有以下场景:

首次启动时,用户可以注册一个帐户。 然后,应用程序从我的网络服务器获取一对(int user_id,string session_id),并将该数据存储在应用程序中。

在我的应用程序中,我使用WebView,让用户查看我的网站的一些内容。 使用user_id和session_id,他自动登录(之后,创建服务器端会话和cookie)。

我不想使用像http://mobile.mysite.com/?user_id=int&session_id=string这样的url方案,所以我决定使用http post发送user_id和session_id。

在iOS中它非常简单:

// Post the user data and load the website in the webview NSString *startUrl = @"http://mobile.mysite.com/"; NSString *post = [NSString stringWithFormat:@"user_id=%@&session_id=%@, [user uid], [user sessionId]]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:startUrl]]; [request setHTTPMethod:@"POST"]; [request setHTTPBody:[post dataUsingEncoding: NSUTF8StringEncoding]]; [webView loadRequest:request]; 

所以在这里,我在C#中的Windows 8商店应用程序中完成了相同的结构。 不幸的是,WebView不允许我将用户信息发布到服务器。

你知道如何解决我的问题吗?

一个想法是创建一个http请求并与WebView共享cookie。 但这对我来说并不是很优雅……

在Windows 8.1中使用WebView进行POST

甚至更好,使用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进行POST

对于Windows 8,使用JavaScript进行操作!

  1. 创建

    ,将action设置为目标URI并将method设置为POST。

  2. 添加两个并使用您想要的名称命名它们,在本例中为user_idsession_id
  3. 添加一个设置输入值并提交表单的脚本。

例如:

 protected override void OnNavigatedTo(NavigationEventArgs e) { webView.NavigateToString(@"     
"); } 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 

您可以做的是发出http请求并将您获得的响应作为字符串。 完成后,您可以调用webView.NavigateToString(responseString) 。 如果你需要css,那么你总是可以将CSS添加到html字符串中。

我认为这种情况通常是如何处理的。

更新:

stackoverflow答案作为参考: https : //stackoverflow.com/a/13862424/329928

关于css的另一个stackoverflow答案: https : //stackoverflow.com/a/14608917/329928