c# - WebRequest 相当于 CURL 命令

标签 c# curl

我正在用头撞墙试图将有效的 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.

如有任何帮助,我们将不胜感激!

谢谢

最佳答案

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

关于c# - WebRequest 相当于 CURL 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21255725/

相关文章:

c# - WPF 自定义用户控件 - "The member X is not recognized or accessible"

c# - 在 XNA/C# 中添加自定义光标?

c# - 挣扎于线程?

date - elasticsearch 中的日期舍入如何工作,它如何影响缓存流失?

php - 使用 PHP 从 URL 保存图像(保存为 0KB 文件大小)

c# - 禁用时 TextBoxFor 值未传递给模型

c# - ASP.NET 将 PDF 写入文件系统

python - 使用 API 从 Box 位置下载文件

c++ - 将两个 dll 添加到 msvc 2010 应用程序

C + cURL + SQLite - CURLINFO_RESPONSE_CODE 破坏了一些甚至与之无关的东西