【发布时间】:2021-07-07 01:41:41
【问题描述】:
我在 Windows 10 上的 Visual Studio 中使用 C# 编写了示例代码,该代码尝试将带有自定义标头的 POST 请求发送到在 http://localhost:9998 上运行的服务失败。
当我查看请求时,Content-Type 标头字段作为 ContentType(无连字符)发送。
httpRequestMessage:方法: POST, RequestUri: 'http://localhost:9998/', 版本:1.1,内容:System.Net.Http.ByteArrayContent,标题:{
内容类型:application/vnd.com.documents4j.any-msword 接受: application/pdf Converter-Job-Priority: 1000 }response:StatusCode: 500,ReasonPhrase:“请求失败。”,版本:1.1,内容: System.Net.Http.StreamContent,标头:{ 连接:关闭日期: 2021 年 4 月 10 日星期六 22:39:24 GMT 内容长度:1031 内容类型: 文本/html; charset=ISO-8859-1 }按任意键继续。 . .
我想知道这是否是问题的原因?
我用 C# 编写的代码使用 RestSharp 并正确发送 Content-Type 并返回成功的结果。 我有用 Java 编写的代码,它也可以正确发送 Content-Type 并返回成功的结果。
示例代码 1 [将 Content-Type 作为 ContentType 发送的问题]
using System;
using System.Net;
using System.IO;
using System.Net.Http;
namespace HttpPOST10
{
class Program
{
public static string MyUri { get; private set; }
static void Main(string[] args)
{
// string url = "http://localhost:9998";
string url = "http://localhost:8888"; // Fiddler
Uri myUri = new Uri(url);
string srcFilename = @"C:\temp2\Sample.doc";
string destFileName = @"C:\temp3\Sample-HttpPOST10.pdf";
UploadFile(url, srcFilename, destFileName);
}
private static bool UploadFile(string url, string srcFilename, string destFileName)
{
HttpClient httpClient = new HttpClient();
byte[] data;
data = File.ReadAllBytes(srcFilename);
var httpRequestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(url),
Headers = {
{ HttpRequestHeader.ContentType.ToString(), "application/vnd.com.documents4j.any-msword" },
{ HttpRequestHeader.Accept.ToString(), "application/pdf" },
{ "Converter-Job-Priority", "1000" },
// {"User-Agent", "RestSharp/106.11.8.0" }
},
Content = new ByteArrayContent(data)
};
Console.Write("httpRequestMessage:" + httpRequestMessage);
var response = httpClient.SendAsync(httpRequestMessage).Result;
Console.Write("response:" + response);
return true;
}
}
}
【问题讨论】:
-
您不能像那样设置
HttpRequestMessage的标头——将Content-Type标头添加到Content.Headers(使用其Add()方法)(在您创建内容之后)。
标签: c# httpclient content-type