Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/api/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# GDax API GET请求始终返回错误400_C#_Api - Fatal编程技术网

C# GDax API GET请求始终返回错误400

C# GDax API GET请求始终返回错误400,c#,api,C#,Api,我试图从GDAX(调用文档的链接)获取订单,但从c#可执行文件获取订单时,我总是收到错误400-请求错误 当获取实际URL并将其粘贴到我的浏览器中时,效果很好 String URL = "https://api.gdax.com/products/BTC-USD/book?level=2"; WebRequest request = WebRequest.Create(URL); WebResponse response = request.GetResponse(); 您需要接受谷歌认证才能

我试图从GDAX(调用文档的链接)获取订单,但从c#可执行文件获取订单时,我总是收到错误400-请求错误

当获取实际URL并将其粘贴到我的浏览器中时,效果很好

String URL = "https://api.gdax.com/products/BTC-USD/book?level=2";
WebRequest request = WebRequest.Create(URL);
WebResponse response = request.GetResponse();

您需要接受谷歌认证才能访问https webrequest


API调用的实际问题是,API在发出请求时需要一个用户代理字符串:下面是处于工作状态的代码:

        try
        {

            String URL = "http://api.gdax.com/products/BTC-USD/book?level=2";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);                
            request.UserAgent = ".NET Framework Test Client";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            var encoding = ASCIIEncoding.ASCII;
            using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
            {
                string responseText = reader.ReadToEnd();
            }

        }
        catch(WebException ex)
        {
            HttpWebResponse xyz = ex.Response as HttpWebResponse;
            var encoding = ASCIIEncoding.ASCII;
            using (var reader = new System.IO.StreamReader(xyz.GetResponseStream(), encoding))
            {
                string responseText = reader.ReadToEnd();
            }
        }
基本上ProtocolError表示您已收到响应,但在从exception读取响应内容时,您可以观察到与协议相关的错误。我添加了catch来处理异常和read ex.Response(即HttpWebResponse),可以看到API在调用时请求支持用户代理。我看到错误为“{”消息“:“需要用户代理头。”}”

您可以忽略异常块中的代码,我使用它只是为了查看实际的响应消息,其中包含实际的错误详细信息

注意:我已将WebRequest装箱到HttpWebRequest,以具有附加的http协议相关属性,最重要的是WebRequest类中不可用的“UserAgent”属性