HTTP 클라이언트에서 Accept, ContentType 및 Authentication with headers를 사용하여 POST를 만드는 데 문제가 있습니다. 나는 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) 및 상대 URL (예 : (api/house))? Fiddler로 요청을 검사 할 수도 있습니다. http://www.telerik.com/fiddler –
나는 당신이 옳다고 생각합니다. 변경 및 여전히 연결 시간 초과 오류가 발생했습니다 – PLOW
문제가 해결되었습니다. 코드가 정확합니다. 문제는 내가 학교 프록시를 사용하고있어서 프록시가 해제 되었기 때문입니다. 집에 돌아가서 Wi-Fi를 사용하면 시간이 없습니다. 오류. – PLOW