【问题标题】:postAsync with header and content c#postAsync 与标题和内容 c#
【发布时间】:2016-08-05 14:12:22
【问题描述】:

我需要postAsync 与标题和内容一起。为了通过 C# 中的控制台应用程序访问网站。我将标题作为具有变量名称标题的HttpHeader 对象,并将我的内容命名为newContent 作为具有__TokenreturnEmailPassword 的字符串对象。现在我要做的是将 newContent 添加到标题中,然后使用 postAsync(url, header+content) 发出我的 POST 请求。

public async static void DownloadPage(string url)
{
    CookieContainer cookies = new CookieContainer();
    HttpClientHandler handler = new HttpClientHandler();
    handler.CookieContainer = cookies;

    using (HttpClient client = new HttpClient(handler))
    {
        using (HttpResponseMessage response = client.GetAsync(url).Result)
        {
            //statusCode
            CheckStatusCode(response);
            //header
            HttpHeaders headers = response.Headers;
            //content
            HttpContent content = response.Content;
            //getRequestVerificationToken&createCollection
            string newcontent = CreateCollection(content);

            using(HttpResponseMessage response2 = client.PostAsync(url,))

        }

    }
}

public static string GenerateQueryString(NameValueCollection collection)
{
    var array = (from key in collection.AllKeys
                 from value in collection.GetValues(key)
                 select string.Format("{0}={1}", WebUtility.UrlEncode(key), WebUtility.UrlEncode(value))).ToArray();
    return string.Join("&", array);
}


public static void CheckStatusCode(HttpResponseMessage response)
{
    if (response.StatusCode != HttpStatusCode.OK)
        throw new Exception(String.Format(
       "Server error (HTTP {0}: {1}).",
       response.StatusCode,
       response.ReasonPhrase));
    else
        Console.WriteLine("200");
}
public static string CreateCollection(HttpContent content)
{
    var myContent = content.ReadAsStringAsync().Result;
    HtmlNode.ElementsFlags.Remove("form");
    string html = myContent;
    var doc = new HtmlAgilityPack.HtmlDocument();
    doc.LoadHtml(html);
    var input = doc.DocumentNode.SelectSingleNode("//*[@name='__Token']");
    var token = input.Attributes["value"].Value;
    //add all necessary component to collection
    NameValueCollection collection = new NameValueCollection();
    collection.Add("__Token", token);
    collection.Add("return", "");
    collection.Add("Email", "11111111@hotmail.com");
    collection.Add("Password", "1234");
    var newCollection = GenerateQueryString(collection);
    return newCollection;
}

【问题讨论】:

  • 什么意思?我只是不知道该怎么做...@x...

标签: c# httpclient httpcookie httpresponsemessage


【解决方案1】:

我昨天做了同样的事情。我为我的控制台应用程序创建了一个单独的类,并将 HttpClient 的东西放在那里。

在主要:

_httpCode = theClient.Post(_response, theClient.auth_bearer_token);

在课堂上:

    public long Post_RedeemVoucher(Response _response, string token)
    {
        string client_URL_voucher_redeem = "https://myurl";

        string body = "mypostBody";

        Task<Response> content = Post(null, client_URL_voucher_redeem, token, body);

        if (content.Exception == null)
        {
            return 200;
        }
        else
            return -1;
    }

然后是调用本身:

    async Task<Response> Post(string headers, string URL, string token, string body)
    {
        Response _response = new Response();

        try
        {
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, URL);
                request.Content = new StringContent(body);

                using (HttpResponseMessage response = await client.SendAsync(request))
                {
                    if (!response.IsSuccessStatusCode)
                    {
                        _response.error = response.ReasonPhrase;
                        _response.statusCode = response.StatusCode;

                        return _response;
                    }

                    _response.statusCode = response.StatusCode;
                    _response.httpCode = (long)response.StatusCode;

                    using (HttpContent content = response.Content)
                    {
                        _response.JSON = await content.ReadAsStringAsync().ConfigureAwait(false);
                        return _response;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            _response.ex = ex;
            return _response;
        }
    }

我希望这能为您指明正确的方向!

【讨论】:

  • 非常感谢。我一回到家就试试看,然后告诉你进展如何:)
  • 是我还是你从不使用你的标题@GrahamJ
【解决方案2】:

如何遍历您的 Headers 并将它们添加到 Content 对象:

var content = new StringContent(requestString, Encoding.UTF8);

// Iterate over current headers, as you can't set `Headers` property, only `.Add()` to the object.
foreach (var header in httpHeaders) { 
    content.Headers.Add(header.Key, header.Value.ToString());
}

response = client.PostAsync(Url, content).Result;

现在,它们以一种方法发送。

【讨论】:

  • 很好,我回家后会试一试,然后告诉你进展如何。l
  • 不能像那样添加“标题”...我尝试使用 header.key 作为名称,使用 header.value.Tostring() 作为值,但它不起作用。它给出了以下错误 Misused header name。确保请求标头与 HttpRequestMessage 一起使用,响应标头与 HttpResponseMessage 一起使用,内容标头与 HttpContent 对象一起使用。
  • 我不能用这个作为代码:HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url); request.Content = new StringContent(queryString); foreach (var header in headers) { request.Content.Headers.Add(header.Key,header.Value.ToString()); }@Nick Bull
  • @Puzzle 很抱歉,我是通过手机回答的,所以没有 IDE 可以测试!您要插入的值是什么?这听起来像是您插入的标题类型的问题。确保它是一个有效的内容标头(有关其他人收到您的错误消息的示例,请参见此处:stackoverflow.com/questions/10679214/…
  • 所以请尝试就您插入的无效值与我联系
【解决方案3】:

如果您仍在研究此问题,您还可以在请求级别以及HttpClient 级别添加标头。这对我有用:

HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, URL);

request.Content = new StringContent(body);

request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

【讨论】:

  • cookies 怎么样?我似乎无法使用从 getAsync 获得的 cookie 发布请求...
猜你喜欢
  • 2019-03-08
  • 1970-01-01
  • 2021-01-26
  • 2018-06-06
  • 2012-05-08
  • 1970-01-01
  • 2015-03-30
  • 2018-03-12
  • 1970-01-01
相关资源
最近更新 更多