在 C# 中将请求 headers 传递给 HttpWebRequest

Passing request headers to HttpWebRequest in C#

我正在尝试创建一个 HttpWebRequest 并从中获取 json 数据。使用 Postman,当我设置 url、参数和 headers 时,我能够得到 json 响应(请参阅 this)。但是,当我尝试使用 C# 时,我没有得到任何响应。

我在 Whosebug 上搜索了几篇帖子并按照步骤操作,但找不到问题所在或是否需要其他任何内容。

        string requestUrl = Constants.FLIPKART_INSTALLS_URL;
        requestUrl = requestUrl.Replace("##STARTDATE##", DateTime.Now.ToString("yyyy-MM-dd"));
        requestUrl = requestUrl.Replace("##ENDDATE##", DateTime.Now.ToString("yyyy-MM-dd"));

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);
        //request.Credentials = CredentialCache.DefaultCredentials;
        request.Method = "GET";
        //request.ContentType = "application/json";
        request.Headers["Fk-Affiliate-id"] = Constants.FLIPKART_AFFILIATE_ID;
        request.Headers["Fk-Affiliate-token"] = Constants.FLIPKART_AFFILIATE_TOKEN;
        WebResponse response = request.GetResponse();

This 是我得到的回复。我不确定这是否真的是一个愚蠢的问题,但由于我对 C# 了解不多,所以我发布了它。 提前致谢。

通过在响应对象上调用 GetResponseStream(),我能够读取内容,如果需要请参考下面的代码:

using System;
using System.Net;
using System.Text;
using System.IO;

public class Test
{
    // Specify the URL to receive the request.
    public static void Main (string[] args)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create (args[0]);

        // Set some reasonable limits on resources used by this request
        request.MaximumAutomaticRedirections = 4;
        request.MaximumResponseHeadersLength = 4;
        // Set credentials to use for this request.
        request.Credentials = CredentialCache.DefaultCredentials;
        HttpWebResponse response = (HttpWebResponse)request.GetResponse ();

        Console.WriteLine ("Content length is {0}", response.ContentLength);
        Console.WriteLine ("Content type is {0}", response.ContentType);

        // Get the stream associated with the response.
        Stream receiveStream = response.GetResponseStream ();

        // Pipes the stream to a higher level stream reader with the required encoding format. 
        StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);

        Console.WriteLine ("Response stream received.");
        Console.WriteLine (readStream.ReadToEnd ());
        response.Close ();
        readStream.Close ();
    }
}