Alice52 / c-tutorial

The repository is about c, including c, csharp, cpp.
MIT License
0 stars 0 forks source link

[http client] api call #8

Open Alice52 opened 4 years ago

Alice52 commented 4 years ago

core: this is important, so we can use fiddler to trace this http detail

  1. uri: this may lead to 404
  2. method: this may lead 405
  3. header:
    • content-type cannot be set in common, otherwise will lead to Misused header name.
    • fortunately, can set by xxContent for each request
  4. body:
    • get request has no body
    • post request body type is decisive for this request, common is application/json

http client[such as named client]

// startup.cs
private void InjectClients(IServiceCollection services)
{
    services.AddHttpClient(ClientsConstants.TABLE_SERVICE_CLIENT, client =>
        {
                client.BaseAddress = new Uri("http://localhost:8080/xxx/");
                client.Timeout = TimeSpan.FromMilliseconds(10 * 1000));
        });
}

// util.cs
public static T Post<T>(IHttpClientFactory factory, string ClientName, object body, string servicePath)
{
    var jsonBody = JsonUtil.SerializeObject(body, DateFormatHandling.MicrosoftDateFormat);

    var client = factory.CreateClient(ClientName);
    StringContent content = new StringContent(jsonBody);
    content.Headers.ContentType = new MediaTypeHeaderValue("aplication/json");

    var response = client.PostAsync(servicePath, content).Result;
    var responseContent = response.Content.ReadAsStringAsync().Result;

    if (!response.IsSuccessStatusCode)
    {
        throw new Exception("Get data from TableService failed. URI: "
                + response.RequestMessage.RequestUri + ", Error Message: " + responseContent);
    }

    return JsonUtil.DeserializeObject<T>(responseContent);
}

// usage: notice _clientFactory is get from IOC container
HttpUtil.Post<ReceiveTableInventory>(_clientFactory, CLIENT_NAME, a, SERVICE_PATH);

rest client: is same as http client

  1. content-type is "application/json`
  2. request.AddJsonBody(jsonBody);
public static IRestResponse Post(string requestPath, int timeout, object jsonBody, IDictionary<string, string> headerParams, string clientPath)
{
    var request = new RestRequest(requestPath, Method.POST) { Timeout = timeout };
    // request.AddHeader("Content-Type", "application/json");
    // request.RequestFormat = DataFormat.Json;

    if (headerParams != null && headerParams.Count > 0)
    {
        foreach (string key in headerParams.Keys)
        {
            request.AddHeader(key, headerParams[key]);
        }
    }

    if (jsonBody != null)
    {
        request.AddJsonBody(jsonBody);
    }

    var client = new RestClient(clientPath);

    return client.Execute(request);
}
  1. content-type is "application/x-www-form-urlencoded`
public JWTTokenModel getAccessToken()
{
    var request = new RestRequest(Path, Method.POST) { Timeout = 10000 };
    // make no sense
    request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
    StringBuilder sb = new StringBuilder();
    sb.Append("grant_type=").Append(_grantType)
        .Append("&username=").Append(_userName)
        .Append("&password=").Append(_password);
    var client = new RestClient(_baseUrl);
    client.Authenticator = new HttpBasicAuthenticator(_oAuthClientKey, _oAuthClientSecret);
    // special
    request.AddParameter("application/x-www-form-urlencoded", sb.ToString(), ParameterType.RequestBody);
    client.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
    var response = client.Execute(request);

    if (response.IsSuccessful)
    {
        return JsonConvert.DeserializeObject<JWTTokenModel>(response.Content);
    }
    else
    {
        if (response.ErrorException != null)
        {
            _logger.LogWarning("Get token fialed from identity server, cause by: " + response.ErrorException.StackTrace);
        }
        else
        {
            // handle IS Server client donot exist case, which is specify
            // due to IS Server will return error message in content rather than in ErrorException
            _logger.LogWarning("Get token fialed from identity server, cause by: " + response.Content);
        }

    }

    return null;
}