对c#HttpClient的等效curl请求

时间:2016-10-14 05:53:48

标签: c# httpclient

如何在c#HttepClient中进行以下curl请求

curl -X POST“https://api.knurld.io/v1/endpointAnalysis/file”  -H“授权:$ AUTHORIZATION”\  -H“Developer-Id:$ DEVELOPER_ID”\  -H“multipart / form-data”\  -F“filename = PATH_TO_FILE”

2 个答案:

答案 0 :(得分:0)

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

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

亲切的问候

答案 1 :(得分:0)

对于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();
            }
        }
    }