1
我在使用http客戶端使用Accept,ContentType和Authentication作爲標題進行POST時遇到問題。我嘗試了幾個使用send aysnc和post async的實現,並且都失敗了。我使用https://www.hurl.it/來確定它是否也出現超時錯誤,但它正在工作,找回json數據。超時錯誤:HttpClient POST
運行下面的代碼時,出現連接超時錯誤異常(在: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,不應該是基地址(例如。 https://somewebsite.com)和相關的網址(例如(api/house)?您還可以使用Fiddler檢查您的請求http://www.telerik.com/fiddler –
我認爲您是正確的。改變,仍然有連接超時錯誤 – PLOW
問題已經解決!代碼是正確的。問題是,我使用校園的無線網絡,所以我在一個代理服務器。回家,使用我的wifi給我沒有時間錯誤 – PLOW