【发布时间】:2017-03-17 21:03:39
【问题描述】:
我在使用带有 Accept、ContentType 和 Authentication 作为标头的 http 客户端进行 POST 时遇到问题。我尝试了几种使用 send aysnc 和 post async 的实现,但似乎都失败了。我使用https://www.hurl.it/ 来确定它是否也出现超时错误,但它正在工作,正在取回 json 数据。
运行以下代码时出现连接超时错误异常(在:var response = await client.SendAsync(request);)。
我还有 curl 命令,我试图通过它来执行,下面也列出了。
实施:
// Body
var dictionary = new Dictionary<string, string>();
dictionary.Add("id", "123");
var formData = new List<KeyValuePair<string, string>>();
formData.Add(new KeyValuePair<string, string>("id", "123"));
// Http Client
var client = new HttpClient();
client.BaseAddress = new Uri("https://www.some_website.com/api/house");
// Http Request
var request = new HttpRequestMessage(HttpMethod.Post, "https://www.some_website.com/api/house");
// Accept
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Content-Type
//request.Content = new FormUrlEncodedContent(dictionary);
var httpContent = new StringContent(
JsonConvert.SerializeObject(
dictionary,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
}),
Encoding.UTF8,
"application/json");
request.Content = new StringContent(
JsonConvert.SerializeObject(
dictionary,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
}),
Encoding.UTF8,
"application/json");
// Authentication
var byteArray = new UTF8Encoding().GetBytes("user" + ":" + "pass");
//client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
var header = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
client.DefaultRequestHeaders.Authorization = header;
// Communication
try
{
var response = await client.SendAsync(request);//PostAsync("https://www.some_website.com/api/house", httpContent);
if (response.IsSuccessStatusCode)
{
var myContent = await response.Content.ReadAsStringAsync();
var deliveryStatus = JsonConvert.DeserializeObject<MyOjbect>(myContent);
}
}
catch (Exception e)
{
//catch error
}
卷曲:
curl -i --user user:123 -H Accept:application/json -H content-type:application/json -H cache-control:no-cache -X POST https://www.some_website.com/api/house -H Content-Type: application/json -d '{"id": "123"}'
【问题讨论】:
-
您将 BaseAddress 和 HttpRequestMessage Uri 属性都设置为相同的绝对 url,不应该是基地址(例如 somewebsite.com)和相对 url(例如 (api/house )? 您也可以使用 Fiddler telerik.com/fiddler 检查您的请求
-
我认为你是对的。我进行了更改,但仍然出现连接超时错误
-
问题已解决!代码是正确的。问题是我使用的是校园wifi,所以我在代理后面。回家并使用我的 wifi 不会让我出现超时错误。
-
JimmyH 您的建议是解决方案的一部分。如果您可以发布具有相同建议的答案帖子,我可以将其标记为答案。
标签: c# rest http-headers httpclient http-authentication