我需要postAsync
标题和内容在一起。为了通过C#中的控制台应用程序访问网站。我将我的标题作为HttpHeader
对象,其变量名称标题和我的内容名为newContent
作为字符串对象__Token
,return
,Email
和{{ 1}}。现在我要做的是将newContent添加到标头,然后使用Password
发出我的POST请求。
postAsync(url, header+content)
答案 0 :(得分:1)
在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");