如何设置HttpClient的内容类型 [英] How to set the Content Type of 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屋!