如何设置HttpClient的内容类型 [英] How to set the Content Type of HttpClient

查看:128
本文介绍了如何设置HttpClient的内容类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在上传图片.

我想设置Content-Type ="multipart/form-data; boundary = ---- WebKitFormBoundaryFoxUxCRayQhs5eNN"的值

I want to set the value of Content-Type="multipart/form-data; boundary=----WebKitFormBoundaryFoxUxCRayQhs5eNN"

使用代码:

HttpRequestMessage request=new HttpRequestMessage();
request.Content.Headers.ContentType="multipart/form-data; boundary=----WebKitFormBoundaryFoxUxCRayQhs5eNN";

request.Header.ContentType="multipart/form-data; boundary=----WebKitFormBoundaryFoxUxCRayQhs5eNN";

这将导致错误:其中一个已识别的项目格式无效.

it will cause an error:one of the identified items was in an invalid format.

如果仅设置"multipart/form-data",则可以,但是无法上传文件.

if only set of "multipart/form-data" it will be ok but can not upload the file.

如何设置?

推荐答案

以下是一些代码片段,您可以参考:

Here are some code snippets you can refer to:

  using (var client = new HttpClient())
  using (var fileStream = File.Open(fileName, FileMode.Open, FileAccess.Read)
  using (var streamContent = new StreamContent(fileStream))
  {
     streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
     streamContent.Headers.ContentDisposition.Name = "\"file\"";
     streamContent.Headers.ContentDisposition.FileName = "\"" + fileName + "\"";
     streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
     string boundary = "WebKitFormBoundaryFoxUxCRayQhs5eNN";

     var fContent = new MultipartFormDataContent(boundary);
     fContent.Headers.Remove("Content-Type");
     fContent.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary);
     fContent.Add(streamContent);

     var response = await client.PostAsync(new Uri(url), fContent);
     response.EnsureSuccessStatusCode();
  }

如果您使用HttpWebRequest,则可以参考以下内容: https://stackoverflow.com/a/20000831/10768653

if you use HttpWebRequest,you could refer to this:https://stackoverflow.com/a/20000831/10768653

这篇关于如何设置HttpClient的内容类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆