使用HttpClient的多个自定义请求标头条目

时间:2015-07-19 22:19:24

标签: c# asp.net

在发送请求之前,我想为我的httpclient对象提供多个自定义请求标头条目。我想发送的请求应如下所示:

Request Headers     
Connection:keep-alive
Content-Length:213
Content-Type:application/json     
Host:portal.idtbeyond.com
Origin:https://portal.idtbeyond.com
Referer:https://portal.idtbeyond.com/activedocs
x-idt-beyond-app-id:xxccccxx
x-idt-beyond-app-key:yyuuuttttddfdfdfdfdfd
X-Requested-With:XMLHttpRequest
Request Payload
view parsed
{
   "country_code": "SV",
   "carrier_code": "Claro",
   "mobile_number": "50363751234",
   "plan": "Sandbox",
   "amount": "500",
   "client_transaction_id": "",
   "terminal_id": "KIOSK 1",
   "origin_country": "US"
}

我在C#中编写的代码如下:

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri(_ProviderService.GatewayUrl);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(
        new  MediaTypeWithQualityHeaderValue("application/json"));
    client.DefaultRequestHeaders.Add("x-idt-beyond-app-id",
       _PayingMerchant.Username);
    client.DefaultRequestHeaders.Add("x-idt-beyond-app-key", 
       _PayingMerchant.Password);
    var urlSuffix = GetUrlSuffix(trans);                  

    HttpResponseMessage response = client.GetAsync(urlSuffix).Result;
    if (response.IsSuccessStatusCode)
        {
            TopUpResponse topUpResponse = 
               response.Content.ReadAsAsync<TopUpResponse>().Result;
            if (topUpResponse.success)
            {
                result.Success = true;
                result.ReturnValue = true;
            }
        }
    }

我收到了404响应并且调试显示标题部分对我来说是错误的。我是这些要求的新手,并希望得到任何帮助。

此致

1 个答案:

答案 0 :(得分:0)

尝试设置referer以及如下:

client.DefaultRequestHeaders.Referer = https://portal.idtbeyond.com/activedocs

确保使用正确的GatewayUrl