4

I'm trying to get the order book from GDAX (link to documentation of the call) but when doing it from the c# executable I always get Error 400 - Bad request.

When taking the actual URL and pasting it into my browser, it works fine.

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

2 Answers2

8

The actual issue with your API call is , the API is expecting a user-agent string while making the request: Below is the code in working condition:

        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();
            }
        }

Basically ProtocolError indicates that you have received the response but there is an error related to protocol, which you can observe, when you read the response content from exception. I have added catch to handle the exception and read ex.Response (which is HttpWebResponse) and could see that the API is asking for user-agent to be suppllied while making the call. I got to see the error as "{"message":"User-Agent header is required."}"

You can ignore the code inside the exception block, I used it only to see what is the actual response message, which contains actual error details

Note: I have boxed WebRequest to HttpWebRequest to have additional http protocol related properties and most importantly "UserAgent" property which is not available with the WebRequest class.

Sujith
  • 1,604
  • 9
  • 16
0

You need to Accept the certificarte, Google for access to a https webrequest.

Like this