当我使用HttpClient
类向 API URL 发送 POST 请求时,它会修改我传递给它的 URL。例如,当我使用主 API URL 时,RequestUri
不正确,并且收到未找到响应。当我在 URL 中使用api
单词时,就会发生此问题!!
概念:
The Incorrect, modified URL:
Url: https://sandbox-api.alopeyk.com/api/v2/order
Request Url: https://sandbox-api.alopeyk.com
The Correct, and expected URL (This is the one I specify)
Url: https://google.com/api/v2/order
Request Url: https://google.com/api/v2/order
法典:
public async Task<CreateOrderResponse> CreateOrderAsync(CreateOrderRequest request)
{
var endPoint = EndPointFactory<CreateOrderResponse>.Build(HttpMethod.Post);
var jsonString = JsonConvert.SerializeObject(request);
var url = new Uri("https://sandbox-api.alopeyk.com");
var encodedFrom = new StringContent(jsonString);
var httpClient = endPoint.GetHttpClient(url);
var httpResponse = await httpClient.PostAsync("api/v2/orders", encodedFrom).ConfigureAwait(false);
// when use api it's https://sandbox-api.alopeyk.com it should be https://sandbox-api.alopeyk.com/api/v2/orders
// when use other host name for example it's correct
var requesturl = httpResponse.RequestMessage.RequestUri;
return await httpResponse.Content.ReadAsAsync<CreateOrderResponse>().ConfigureAwait(false);
}
// in the EndPoint class
public HttpClient GetHttpClient(Uri url)
{
return new Http.HttpClientFactory().GetOrCreate(Url, Headers);
}
如果你想看看HttpClientFactory
它就在这里。
HttpClient
我的主要主机名有问题,它https://sandbox-api.alopeyk.com
您的 Uri 必须以如下斜杠结尾:
var url = new Uri("https://sandbox-api.alopeyk.com/");
这是HttpClient的一个相当愚蠢的限制。
试试这段代码:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://sandbox-api.alopeyk.com");
HttpResponseMessage response = client.PostAsync("api/v2/orders", new StringContent(jsonString, Encoding.UTF8, "text/json")).Result;
if (response.IsSuccessStatusCode)
{
// Parse the response body. Blocking!
var responseData = response.Content.ReadAsStringAsync().Result;
}
你可以试试这段代码
HttpResponseMessage response = null;
using (var client = new HttpClient())
{
using (var request = new HttpRequestMessage(HttpMethod.Post,"https://sandbox-api.alopeyk.com/api/v2/orders"))
{
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", /*token herer*/);
var data = new StringContent(JsonConvert.SerializeObject(request, Encoding.UTF8, "application/json"));
request.Content = data;
response = await client.SendAsync(request);
}
}