【问题标题】:Equivalent curl request to c# HttpClient等效于 c# HttpClient 的 curl 请求
【发布时间】:2016-10-14 14:45:16
【问题描述】:

如何在 c# HtepClient 中发出以下 curl 请求

curl -X 发布“https://api.knurld.io/v1/endpointAnalysis/file”\ -H "授权:$AUTHORIZATION" \ -H "开发者 ID:$DEVELOPER_ID" \ -H“多部分/表单数据”\ -F "文件名=PATH_TO_FILE"

【问题讨论】:

    标签: c# httpclient


    【解决方案1】:

    这是同步实现,但我希望是你需要的

        public void Send(string auth, string filePath, string developerId)
        {
            string payload = System.IO.File.ReadAllText(filePath);
            var content = new StringContent(payload);
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", auth);
                client.DefaultRequestHeaders.Add("Content-Type", "multipart/form-data");
                client.DefaultRequestHeaders.Add("Developer-Id", developerId);
                var result = client.PostAsync("https://api.knurld.io/v1/endpointAnalysis/file", content).Result;
                string resultContent = result.Content.ReadAsStringAsync().Result;
            }
        }
    

    亲切的问候

    【讨论】:

    • 对于异步相关的东西我想要它使用 HttpClient
    【解决方案2】:

    对于 HttpClient:

    async Task Send(string developerId, string pathToFile, string auth)
        {
            using (HttpClient c = new HttpClient())
            {
                c.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(auth);
                c.DefaultRequestHeaders.Add("Developer-Id", developerId);
                var multipartFormDataContent = new MultipartFormDataContent();
                using (Stream fileStream = new FileStream(pathToFile, FileMode.Open))
                {
                    multipartFormDataContent.Add(new StreamContent(fileStream));
                    HttpResponseMessage httpResponse = await c.PostAsync(@"https://api.knurld.io/v1/endpointAnalysis/file", multipartFormDataContent);
                    string response = await httpResponse.Content.ReadAsStringAsync();
                }
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-20
      相关资源
      最近更新 更多