C# HttpClient 4.5 multipart/form-data upload

前端 未结 10 1145
逝去的感伤
逝去的感伤 2020-11-22 05:39

Does anyone know how to use the HttpClient in .Net 4.5 with multipart/form-data upload?

I couldn\'t find any examples on the internet.

10条回答
  •  青春惊慌失措
    2020-11-22 05:48

    X509Certificate clientKey1 = null;
    clientKey1 = new X509Certificate(AppSetting["certificatePath"],
    AppSetting["pswd"]);
    string url = "https://EndPointAddress";
    FileStream fs = File.OpenRead(FilePath);
    var streamContent = new StreamContent(fs);
    
    var FileContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result);
    FileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("ContentType");
    var handler = new WebRequestHandler();
    
    
    handler.ClientCertificateOptions = ClientCertificateOption.Manual;
    handler.ClientCertificates.Add(clientKey1);
    handler.ServerCertificateValidationCallback = (httpRequestMessage, cert, cetChain, policyErrors) =>
    {
        return true;
    };
    
    
    using (var client = new HttpClient(handler))
    {
        // Post it
        HttpResponseMessage httpResponseMessage = client.PostAsync(url, FileContent).Result;
    
        if (!httpResponseMessage.IsSuccessStatusCode)
        {
            string ss = httpResponseMessage.StatusCode.ToString();
        }
    }
    

提交回复
热议问题