【问题标题】:WebRequest Equivalent to CURL commandWebRequest 等价于 CURL 命令
【发布时间】:2014-02-10 21:43:25
【问题描述】:

我正用头撞墙,试图将工作的 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.

任何帮助将不胜感激!

谢谢

【问题讨论】:

标签: c# curl


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    这是我使用 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 获取响应,在参数上接收错误。谢谢。
    【解决方案3】:

    这是我用来发布 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);
    }
    

    【讨论】:

      【解决方案4】:

      根据这个关于 406 的问题:What is "406-Not Acceptable Response" in HTTP? 也许您可以尝试在您的请求中添加一个 Accept 标头?也许 curl 会自动添加。

      您的 curl 请求中还有一个 -k 告诉它忽略 SSL 验证,我不确定它是否会影响 .NET 代码。换句话说,没有'-k' curl 仍然可以工作吗?然后,不用担心。否则,也许您需要告诉 .NET 也忽略 SSL 验证。

      【讨论】:

      • 我想你可能会在那里做一些事情......如果没有 -k,curl 将无法工作,而且当我查看时,我可以在通话中看到 Accept: /在提琴手里
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-11
      • 2013-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-02
      • 2021-04-23
      相关资源
      最近更新 更多