14

I am banging my head against a wall trying to convert a working curl command to a c# WebRequest.

I have read through quite a few postings and I was pretty sure I had the code right but it still will not work.

Can anyone see what I am doing wrong please?

Here is the working curl command:

curl -k -u x:reallylongstring -H "Content-Type: application/json"  https://api.somewhere.com/desk/external_api/v1/customers.json

And this is the code I have written in c#:

WebRequest wrGETURL;
wrGETURL = WebRequest.Create("https://api.somewhere.com/desk/external_api/v1/customers.json");
wrGETURL.Method = "GET";
wrGETURL.ContentType = "application/json"; 
wrGETURL.Credentials = new NetworkCredential("x", "reallylongstring");
Stream objStream = wrGETURL.GetResponse().GetResponseStream();
StreamReader objReader = new StreamReader(objStream);
string responseFromServer = objReader.ReadToEnd();

But the api responds:

The remote server returned an error: (406) Not Acceptable.

Any help would be much appreciated!

Thanks

Trevor Daniel
  • 3,785
  • 12
  • 53
  • 89
  • Is this a duplicate of [.net - Making a cURL call in C#](http://stackoverflow.com/questions/7929013/making-a-curl-call-in-c-sharp)? There seems to be more answers there. – Sam Hobbs Jan 03 '17 at 06:13

4 Answers4

11

Based on Nikolaos's pointers I appear to have fixed this with the following code:

public static gta_allCustomersResponse gta_AllCustomers()
    {
        var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.somewhere.com/desk/external_api/v1/customers.json");
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Accept = "*/*";
        httpWebRequest.Method = "GET";
        httpWebRequest.Headers.Add("Authorization", "Basic reallylongstring");

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            gta_allCustomersResponse answer =  JsonConvert.DeserializeObject<gta_allCustomersResponse>(streamReader.ReadToEnd());
            return answer;
        }
    }
Trevor Daniel
  • 3,785
  • 12
  • 53
  • 89
4

Here is my solution to post json data to using an API call or webservice

    public static void PostJsonDataToApi(string jsonData)
    {

        var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.somewhere.com/v2/cases");
        httpWebRequest.ReadWriteTimeout = 100000; //this can cause issues which is why we are manually setting this
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Accept = "*/*";
        httpWebRequest.Method = "POST";
        httpWebRequest.Headers.Add("Authorization", "Basic ThisShouldbeBase64String"); // "Basic 4dfsdfsfs4sf5ssfsdfs=="
        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
           // we want to remove new line characters otherwise it will return an error
            jsonData= thePostBody.Replace("\n", ""); 
            jsonData= thePostBody.Replace("\r", "");
            streamWriter.Write(jsonData);
            streamWriter.Flush();
            streamWriter.Close();
        }

        try
        {
            HttpWebResponse resp = (HttpWebResponse)httpWebRequest.GetResponse();
            string respStr = new StreamReader(resp.GetResponseStream()).ReadToEnd();
            Console.WriteLine("Response : " + respStr); // if you want see the output
        }
        catch(Exception ex)
        {
         //process exception here   
        }

    }
kdnerd
  • 341
  • 3
  • 10
  • streamWriter must be flushed. Otherwise, data won't be attached. Was not able to fetch response from an API, receiving error on params, because of that. Thank you. – Li Li Jul 30 '20 at 13:27
4

This is the curl command I use to post json data:

curl http://IP:PORT/my/path/to/endpoint -H 'Content-type:application/json' -d '[{...json data...}]'

This is equivalent to the above curl command with C#:

var url = "http://IP:PORT/my/path/to/endpoint";
var jsonData = "[{...json data...}]";

using (var client = new WebClient())
{
    client.Headers.Add("content-type", "application/json");
    var response = client.UploadString(url, jsonData);
}
thd
  • 2,023
  • 7
  • 31
  • 45
0

According to this question regarding 406: What is "406-Not Acceptable Response" in HTTP? perhaps you could try adding an Accept header to your request? Maybe curl adds that automatically.

Also there's a -k in your curl request telling it to ignore SSL validation, which I'm not sure if it affects the .NET code. In other words, does curl still work without the '-k'? Then, no worries. Otherwise, perhaps you need to tell .NET to also ignore SSL validation.

Community
  • 1
  • 1
Nikolaos Georgiou
  • 2,792
  • 1
  • 26
  • 32
  • I think you might be onto something there... the curl doesn't work without the -k and also I can see Accept: */* in the call when I look at it in fiddler – Trevor Daniel Jan 21 '14 at 11:11