HttpClient将表单发布到网页会返回相同的页面

时间:2015-05-08 16:00:20

标签: c# asp.net dotnet-httpclient

我在网站上有一个专门用于添加特定实体的网页。我尝试做的是使用C#HttpClient添加此实体。我的步骤顺序如下:

首先,我使用客户端进行身份验证:

public static async Task<CookieCollection> WebPortalLogin(string baseURI, string phoneNo, string pin)
    {

        var cookies = new CookieContainer();
        var handler = new HttpClientHandler()
        {
            CookieContainer = cookies
        };
        var client = new HttpClient(handler);
        var content = new FormUrlEncodedContent(new[]{
            new KeyValuePair<string,string>("page","login"),
            new KeyValuePair<string,string>("noStaticBox",""),
            new KeyValuePair<string,string>("username",phoneNo),                
            new KeyValuePair<string,string>("password",pin),
            new KeyValuePair<string,string>("login","Увійти"),
            new KeyValuePair<string,string>("_reqNo","0"),
        });

        var response = await client.PostAsync(baseURI, content);

        response.EnsureSuccessStatusCode();


        var stringResponse = response.Content.ReadAsStringAsync().Result;
        var cookieJar = cookies.GetCookies(new Uri(baseURI));
        return cookieJar;
    }

然后我发送POST请求到编辑页面,其中包含我要保存的所有数据:

public static async Task<HttpResponseMessage> AddCar(string baseURI, string phoneNo, CookieCollection cookieJar, string carNo, string owner)
    {
        var cookieContainer = new CookieContainer();

        var client = new HttpClient(new HttpClientHandler() { CookieContainer = cookieContainer });

        var content = new FormUrlEncodedContent(new[]{
            new KeyValuePair<string,string>("carNo",carNo),
            new KeyValuePair<string,string>("userName",owner),
            new KeyValuePair<string,string>("page","carNumbers"),
            new KeyValuePair<string,string>("submit","Додати"),
            new KeyValuePair<string,string>("operation","addCar"),
            new KeyValuePair<string,string>("_reqNo","0")
        });
        cookieContainer.Add(new Uri(baseURI), cookieJar);
        var response = await client.PostAsync(baseURI, content);
        var stringResponse = response.Content.ReadAsStringAsync().Result;

        return response;
    }

然而,这个POST请求什么都不做,作为回应我有这个非常编辑页面,虽然当我以正常方式(通过网站)添加此实体时,我得到空响应并且实体已成功保存。已经检查过的cookie - 他们没问题。我唯一能想到的是请求标头,但成功的POST只有常规的,比如Accept,Accept-Encoding等。我可能犯的错误是什么?如何才能发布?注意:所有连接都使用HTTPS。

1 个答案:

答案 0 :(得分:0)

好吧,在搞乱了几个小时后,我发现问题出在请求参数之一而与httpclient无关