WebRequest等同于CURL命令

14

我正在试图将一个可用的curl命令转换为c# WebRequest,但卡在了这个问题上。

我已经阅读了很多帖子,而且最初认为代码是正确的,但它仍然无法工作。

请问有人能看出我做错了什么吗?

以下是可用的curl命令:

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

这是我用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();

但是 API 响应:

The remote server returned an error: (406) Not Acceptable.
任何帮助都将不胜感激!

谢谢。

这是 .net - Making a cURL call in C# 的重复吗?那里似乎有更多的答案。 - Sam Hobbs
4个回答

11

根据Nikolaos的指示,我似乎用以下代码解决了这个问题:

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

4
以下是我的解决方案,用于通过API调用或Web服务发布JSON数据。
    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   
        }

    }

streamWriter必须被刷新。否则,数据将无法附加。由于此原因,在参数上收到API的错误,无法获取响应。谢谢。 - Li Li

4
这是我用来发布JSON数据的curl命令:
curl http://IP:PORT/my/path/to/endpoint -H 'Content-type:application/json' -d '[{...json data...}]'

这相当于使用C#的curl命令:
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);
}

0
根据关于406的问题HTTP中的“406-不可接受响应”是什么?,也许您可以尝试在请求中添加一个Accept头。也许curl会自动添加这个头。
此外,在您的curl请求中有一个-k表示忽略SSL验证,我不确定它是否影响.NET代码。换句话说,如果curl没有使用'-k'仍然能够工作,那么就没有问题。否则,您可能需要告诉.NET也忽略SSL验证。

我认为你可能有所发现... 如果没有使用-k,curl就不起作用,同时当我在Fiddler中查看它时,可以看到调用中的 Accept: */*。 - Trevor Daniel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接