我正在发出http发布请求,并且必须在标题中传递用户名和密码。 这就是我的做法:
client.DefaultRequestHeaders.Accept.Clear();
string jsonObjectA = DataDto.ToJSONString();
HttpContent content = new StringContent(jsonObjectA, Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.Add("userName", "".AppendWebConfigValue("username"));
client.DefaultRequestHeaders.Add("password", "".AppendWebConfigValue("Password"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.BaseAddress = new Uri("https://url/");
httpResponse = client.PostAsync("method/test", content).Result;
请求应该这样:
User-Agent: Fiddler
content-Type : application/json
userName: username
password: password
但是,当我在上面运行代码时,这就是我得到的:
userName:usernamepassword:passwordAccept:application/json
我尝试使用Environment.NewLine添加,但是引发了一个错误,即标头的格式不正确。
如何在单独的行中分别添加2个标头,以便能够从服务器获得响应?
答案 0 :(得分:0)
您可以使用HttpRequestMessage
创建请求并添加所需的标头:
static void Main(string[] args)
{
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var request = new HttpRequestMessage
{
RequestUri = new Uri("https://postb.in/1559160461304-0137126960325"),
Method = HttpMethod.Post,
};
request.Headers.Add("username", "username");
request.Headers.Add("password", "password");
var httpResponse = client.SendAsync(request).Result;
}