发送PostAsync

时间:2019-01-04 09:53:00

标签: c# .net httpclient

如何发送两个不同类型的HttpContent?(FormUrlEncodedContent(用于正文)和StringContent(用于其他标题))

我正在尝试使用POST(登录)通过httpclient访问本地服务器进行html抓取。

在此服务器上,您需要一直保持有效的cookie,否则它将被视为超时,并且您将不得不从登录屏幕重新开始。

因此,我们首先需要通过GET请求访问它,获取并保留Cookie,然后发出POST请求。

        var parameter1 = new FormUrlEncodedContent(new Dictionary<string, string>{
            {"param1","***" },
            {"action","login" },
            {"param2",null } //login form
            );
        var parameter2 = new StringContent("en-GB,en;q=0.9,ja;q=0.8", new UTF8Encoding(), "Accept-Language"); //got locale related error so setting accept-language

        var parameter3 = new StringContent(cookie2b.ToArray()[0],new UTF8Encoding(), "Cookie") //cookies

       //I know HttpContent is abstract so you can absolutely not do this, but hope this conveys my gist
        HttpContent hc = parameter1 + parameter2 + parameter3;

            var response = httpclient.PostAsync(url, hc).Result;
            var responseContent = response.Content.ReadAsStringAsync();
            Console.WriteLine(await responseContent);

            using (FileStream fs = File.Create(@"~/random.html"))
            {
                AddText(fs, await responseContent);
            }

[预期] 按预期方式登录并在指定文件中获取html。

[发生了什么] 我不知道如何,但是仅尝试使用parameter1时出现以下服务器端错误: javax.servlet.jsp.JspException:在中,无法建立解析语言环境

*服务器是内部服务器,但不受我控制,而且我可以从浏览器中完美地看到页面,因此我想对代码进行一些修改,而不是对服务器上的代码进行修改。

1 个答案:

答案 0 :(得分:0)

httpclient.DefaultRequestHeaders.AcceptLanguage =“某些语言环境”

您将看到如何向您的请求添加cookie:

How do I set a cookie on HttpClient's HttpRequestMessage

在异步发布之前执行这些步骤,这应该会有所帮助。