如何发布使用HttpClient?

问题描述:

我能够得到使用HttpClinet类网页如下:如何发布使用HttpClient?

HttpClient client = new HttpClient(); 
HttpResponseMessage response = await client.GetAsync(@"http://59.185.101.2:10080/jsp/Login.jsp"); 
response.EnsureSuccessStatusCode(); 
string responseBody = await response.Content.ReadAsStringAsync(); 

该页面将呈现2个textboes,即用户名密码&。它也会渲染许多隐藏的变量。

我想发布这个呈现的Html到所需的地址,但用我自己的用户名值&密码。 (保留隐变量的其余部分)

我该怎么办呢?


PS:这是一个控制台应用程序POC

+1

谁低估了,关心什么评论? –

+0

目前还不清楚为什么你的问题被低估了。这对我来说看起来是一个有效的问题。 –

你可以使用PostAsync方法:

using (var client = new HttpClient()) 
{ 
    var content = new FormUrlEncodedContent(new[] 
    { 
     new KeyValuePair<string, string>("username", "john"), 
     new KeyValuePair<string, string>("password", "secret"), 
    }); 
    content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); 

    var response = await client.PostAsync(
     "http://59.185.101.2:10080/jsp/Login.jsp", 
     content 
    ); 
    response.EnsureSuccessStatusCode(); 
    var responseBody = await response.Content.ReadAsStringAsync(); 
} 

您必须提供所有您的服务器端脚本需要输入必要的参数在FormUrlEncodedContent内容实例中。

就隐藏变量而言,您必须使用HTML解析器(如HTML敏捷包)解析从第一次调用中检索到的HTML,并将它们包含在POST请求的集合中。

+0

谢谢Darin。我会尝试一下。 –

+0

有没有更好的方法来做到这一点btw? –

+0

restsharp会比html敏捷包更好吗? –