postAsync与标题和内容c#

时间:2016-08-05 14:12:22

标签: c# httpclient httpcookie httpresponsemessage

我需要postAsync标题和内容在一起。为了通过C#中的控制台应用程序访问网站。我将我的标题作为HttpHeader对象,其变量名称标题和我的内容名为newContent作为字符串对象__TokenreturnEmail和{{ 1}}。现在我要做的是将newContent添加到标头,然后使用Password发出我的POST请求。

postAsync(url, header+content)

3 个答案:

答案 0 :(得分:1)

昨天我做了同样的事情。我为我的Console App创建了一个单独的类,并将HttpClient的东西放在那里。

在Main:

_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;
        }
    }

我希望这能指出你正确的方向!

答案 1 :(得分:1)

如何迭代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;

现在,他们用一种方法发送。

答案 2 :(得分:0)

如果您仍在查看此内容,您还可以在请求级别以及HttpClient级别添加标头。这对我有用:

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

request.Content = new StringContent(body);

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