Class ApiClient
java.lang.Object
com.binance.connector.client.common.ApiClient
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final int
static final int
static final int
protected Integer
protected List
<ServerConfiguration> -
Constructor Summary
ConstructorsConstructorDescriptionApiClient
(ClientConfiguration configuration) ApiClient
(ClientConfiguration configuration, BinanceAuthenticationFactory binanceAuthenticationFactory) ApiClient
(ClientConfiguration configuration, BinanceAuthenticationFactory binanceAuthenticationFactory, okhttp3.OkHttpClient okHttpClient) ApiClient
(ClientConfiguration configuration, okhttp3.OkHttpClient okHttpClient) -
Method Summary
Modifier and TypeMethodDescriptionaddDefaultCookie
(String key, String value) Add a default cookie.addDefaultHeader
(String key, String value) Add a default header.okhttp3.Call
buildCall
(String baseUrl, String path, String method, List<Pair> queryParams, List<Pair> collectionQueryParams, Object body, Map<String, String> headerParams, Map<String, String> cookieParams, Map<String, Object> formParams, Set<String> authNames) Build HTTP call with the given options.okhttp3.Request
buildRequest
(String baseUrl, String path, String method, List<Pair> queryParams, List<Pair> collectionQueryParams, Object body, Map<String, String> headerParams, Map<String, String> cookieParams, Map<String, Object> formParams, Set<String> authNames) Build an HTTP request with the given options.okhttp3.RequestBody
buildRequestBodyFormEncoding
(Map<String, Object> formParams) Build a form-encoding request body with the given form parameters.okhttp3.RequestBody
buildRequestBodyMultipart
(Map<String, Object> formParams) Build a multipart (file uploading) request body with the given form parameters, which could contain text fields and file fields.Build full URL by concatenating base path, the given sub path and query parameters.collectionPathParameterToString
(String collectionFormat, Collection value) Formats the specified collection path parameter to a string value.<T> T
deserialize
(okhttp3.Response response, Type returnType) Deserialize response body to Java object, according to the return type and the Content-Type response header.downloadFileFromResponse
(okhttp3.Response response) Download file from the given response.escapeString
(String str) Escape the given string to be used as URL query value.<T> ApiResponse
<T> execute
(okhttp3.Call call) <T> ApiResponse
<T> Execute HTTP call and deserialize the HTTP response body into the given return type.freeFormParameterToPairs
(Object value) Formats the specified free-form query parameters to a list ofPair
objects.getAuthentication
(String authName) Get authentication for the given name.Get authentications (key: authentication name, value: authentication).Get base pathint
Get connection timeout (in milliseconds).okhttp3.Interceptor
getCustomHeadersInterceptor
(Map<String, String> customHeaders) okhttp3.OkHttpClient
Get HTTP clientcom.google.gson.Gson
getJson()
Getter for the fieldkeyManagers
.int
Get read timeout (in milliseconds).okhttp3.Interceptor
getRetryInterceptor
(Integer retryCount, Integer retryBackoff) Get SSL CA cert.The path of temporary folder used to store downloaded files from endpoints with file response.int
Get write timeout (in milliseconds).guessContentTypeFromFile
(File file) Guess Content-Type header from the given file (defaults to "application/octet-stream").<T> T
handleResponse
(okhttp3.Response response, Type returnType) Handle the given response, return the deserialized object when the response is successful.boolean
Check that whether debugging is enabled for this API client.boolean
isJsonMime
(String mime) Check if the given MIME is a JSON MIME.boolean
True if isVerifyingSsl flag is onstatic StringBuilder
joinQueryParameters
(StringBuilder sb, List<Pair> params) Joins query parameters from a Map into a StringBuilder representation.static String
joinQueryParameters
(List<Pair> params) Joins query parameters from a Map into a String representation.parameterToPair
(String name, Object value) Formats the specified query parameter to a list containing a singlePair
object.parameterToPairs
(String collectionFormat, String name, Collection value) Formats the specified collection query parameters to a list ofPair
objects.parameterToString
(Object param) Format the given parameter object into string.prepareDownloadFile
(okhttp3.Response response) Prepare file for downloadvoid
processCookieParams
(Map<String, String> cookieParams, okhttp3.Request.Builder reqBuilder) Set cookie parameters to the request builder, including default cookies.void
processHeaderParams
(Map<String, String> headerParams, okhttp3.Request.Builder reqBuilder) Set header parameters to the request builder, including default headers.sanitizeFilename
(String filename) Sanitize filename by removing path.selectHeaderAccept
(String[] accepts) Select the Accept header's value from the given accepts array: if JSON exists in the given array, use it; otherwise use all of them (joining into a string)selectHeaderContentType
(String[] contentTypes) Select the Content-Type header's value from the given array: if JSON exists in the given array, use it; otherwise use the first one of the array.okhttp3.RequestBody
Serialize the given Java object into request body according to the object's class and the request Content-Type.void
setAccessToken
(String accessToken) Helper method to set access token for the first OAuth2 authentication.void
Helper method to set API key value for the first API key authentication.void
setApiKeyPrefix
(String apiKeyPrefix) Helper method to set API key prefix for the first API key authentication.void
setAWS4Configuration
(String accessKey, String secretKey, String region, String service) Helper method to set credentials for AWSV4 Signaturevoid
setAWS4Configuration
(String accessKey, String secretKey, String sessionToken, String region, String service) Helper method to set credentials for AWSV4 SignaturesetBasePath
(String basePath) Set base pathsetConnectTimeout
(int connectionTimeout) Sets the connect timeout (in milliseconds).setDateFormat
(DateFormat dateFormat) Setter for the fielddateFormat
.setDebugging
(boolean debugging) Enable/disable debugging for this API client.setHttpClient
(okhttp3.OkHttpClient newHttpClient) Set HTTP client, which must never be null.void
setJson
(com.google.gson.Gson json) setKeyManagers
(KeyManager[] managers) Configure client keys to use for authorization in an SSL session.setLenientOnJson
(boolean lenientOnJson) Set LenientOnJson.setLocalDateFormat
(DateTimeFormatter dateFormat) Set LocalDateFormat.setOffsetDateTimeFormat
(DateTimeFormatter dateFormat) Set OffsetDateTimeFormat.void
setPassword
(String password) Helper method to set password for the first HTTP basic authentication.setReadTimeout
(int readTimeout) Sets the read timeout (in milliseconds).setServerIndex
(Integer serverIndex) setServers
(List<ServerConfiguration> servers) setServerVariables
(Map<String, String> serverVariables) setSqlDateFormat
(DateFormat dateFormat) Set SqlDateFormat.setSslCaCert
(InputStream sslCaCert) Configure the CA certificate to be trusted when making https requests.setTempFolderPath
(String tempFolderPath) Set the temporary folder path (for downloading files)setUserAgent
(String userAgent) Set the User-Agent header's value (by adding to the default header map).void
setUsername
(String username) Helper method to set username for the first HTTP basic authentication.setVerifyingSsl
(boolean verifyingSsl) Configure whether to verify certificate and hostname when making https requests.setWriteTimeout
(int writeTimeout) Sets the write timeout (in milliseconds).void
updateParamsForAuth
(Set<String> authNames, List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams, String payload, String method, URI uri) Update query and header parameters based on authentication settings.static String
-
Field Details
-
MIN_FILENAME_SIZE
public static final int MIN_FILENAME_SIZE- See Also:
-
HTTP_TEA_POT
public static final int HTTP_TEA_POT- See Also:
-
HTTP_TOO_MANY_REQS
public static final int HTTP_TOO_MANY_REQS- See Also:
-
servers
-
serverIndex
-
serverVariables
-
-
Constructor Details
-
ApiClient
-
ApiClient
public ApiClient(ClientConfiguration configuration, BinanceAuthenticationFactory binanceAuthenticationFactory) -
ApiClient
-
ApiClient
public ApiClient(ClientConfiguration configuration, BinanceAuthenticationFactory binanceAuthenticationFactory, okhttp3.OkHttpClient okHttpClient)
-
-
Method Details
-
getJson
public com.google.gson.Gson getJson() -
setJson
public void setJson(com.google.gson.Gson json) -
getCustomHeadersInterceptor
-
getRetryInterceptor
-
getBasePath
-
setBasePath
-
getServers
-
setServers
-
getServerIndex
-
setServerIndex
-
getServerVariables
-
setServerVariables
-
getHttpClient
public okhttp3.OkHttpClient getHttpClient()Get HTTP client- Returns:
- An instance of OkHttpClient
-
setHttpClient
Set HTTP client, which must never be null.- Parameters:
newHttpClient
- An instance of OkHttpClient- Returns:
- Api Client
- Throws:
NullPointerException
- when newHttpClient is null
-
isVerifyingSsl
public boolean isVerifyingSsl()True if isVerifyingSsl flag is on- Returns:
- True if isVerifySsl flag is on
-
setVerifyingSsl
Configure whether to verify certificate and hostname when making https requests. Default to true. NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks.- Parameters:
verifyingSsl
- True to verify TLS/SSL connection- Returns:
- ApiClient
-
getSslCaCert
-
setSslCaCert
Configure the CA certificate to be trusted when making https requests. Use null to reset to default.- Parameters:
sslCaCert
- input stream for SSL CA cert- Returns:
- ApiClient
-
getKeyManagers
Getter for the fieldkeyManagers
.- Returns:
- an array of
KeyManager
objects
-
setKeyManagers
Configure client keys to use for authorization in an SSL session. Use null to reset to default.- Parameters:
managers
- The KeyManagers to use- Returns:
- ApiClient
-
setDateFormat
Setter for the fielddateFormat
.- Parameters:
dateFormat
- aDateFormat
object- Returns:
- a
ApiClient
object
-
setSqlDateFormat
Set SqlDateFormat.- Parameters:
dateFormat
- aDateFormat
object- Returns:
- a
ApiClient
object
-
setOffsetDateTimeFormat
Set OffsetDateTimeFormat.- Parameters:
dateFormat
- aDateTimeFormatter
object- Returns:
- a
ApiClient
object
-
setLocalDateFormat
Set LocalDateFormat.- Parameters:
dateFormat
- aDateTimeFormatter
object- Returns:
- a
ApiClient
object
-
setLenientOnJson
-
getAuthentications
Get authentications (key: authentication name, value: authentication).- Returns:
- Map of authentication objects
-
getAuthentication
Get authentication for the given name.- Parameters:
authName
- The authentication name- Returns:
- The authentication, null if not found
-
setUsername
Helper method to set username for the first HTTP basic authentication.- Parameters:
username
- Username
-
setPassword
Helper method to set password for the first HTTP basic authentication.- Parameters:
password
- Password
-
setApiKey
Helper method to set API key value for the first API key authentication.- Parameters:
apiKey
- API key
-
setApiKeyPrefix
Helper method to set API key prefix for the first API key authentication.- Parameters:
apiKeyPrefix
- API key prefix
-
setAccessToken
Helper method to set access token for the first OAuth2 authentication.- Parameters:
accessToken
- Access token
-
setAWS4Configuration
-
setAWS4Configuration
public void setAWS4Configuration(String accessKey, String secretKey, String sessionToken, String region, String service) Helper method to set credentials for AWSV4 Signature- Parameters:
accessKey
- Access KeysecretKey
- Secret KeysessionToken
- Session Tokenregion
- Regionservice
- Service to access to
-
setUserAgent
-
addDefaultHeader
-
addDefaultCookie
-
isDebugging
public boolean isDebugging()Check that whether debugging is enabled for this API client.- Returns:
- True if debugging is enabled, false otherwise.
-
setDebugging
Enable/disable debugging for this API client.- Parameters:
debugging
- To enable (true) or disable (false) debugging- Returns:
- ApiClient
-
getTempFolderPath
The path of temporary folder used to store downloaded files from endpoints with file response. The default value isnull
, i.e. using the system's default temporary folder.- Returns:
- Temporary folder path
- See Also:
-
setTempFolderPath
-
getConnectTimeout
public int getConnectTimeout()Get connection timeout (in milliseconds).- Returns:
- Timeout in milliseconds
-
setConnectTimeout
Sets the connect timeout (in milliseconds). A value of 0 means no timeout, otherwise values must be between 1 andInteger.MAX_VALUE
.- Parameters:
connectionTimeout
- connection timeout in milliseconds- Returns:
- Api client
-
getReadTimeout
public int getReadTimeout()Get read timeout (in milliseconds).- Returns:
- Timeout in milliseconds
-
setReadTimeout
Sets the read timeout (in milliseconds). A value of 0 means no timeout, otherwise values must be between 1 andInteger.MAX_VALUE
.- Parameters:
readTimeout
- read timeout in milliseconds- Returns:
- Api client
-
getWriteTimeout
public int getWriteTimeout()Get write timeout (in milliseconds).- Returns:
- Timeout in milliseconds
-
setWriteTimeout
Sets the write timeout (in milliseconds). A value of 0 means no timeout, otherwise values must be between 1 andInteger.MAX_VALUE
.- Parameters:
writeTimeout
- connection timeout in milliseconds- Returns:
- Api client
-
parameterToString
-
parameterToPair
Formats the specified query parameter to a list containing a singlePair
object.Note that
value
must not be a collection.- Parameters:
name
- The name of the parameter.value
- The value of the parameter.- Returns:
- A list containing a single
Pair
object.
-
parameterToPairs
Formats the specified collection query parameters to a list ofPair
objects.Note that the values of each of the returned Pair objects are percent-encoded.
- Parameters:
collectionFormat
- The collection format of the parameter.name
- The name of the parameter.value
- The value of the parameter.- Returns:
- A list of
Pair
objects.
-
freeFormParameterToPairs
-
collectionPathParameterToString
Formats the specified collection path parameter to a string value.- Parameters:
collectionFormat
- The collection format of the parameter.value
- The value of the parameter.- Returns:
- String representation of the parameter
-
sanitizeFilename
-
isJsonMime
Check if the given MIME is a JSON MIME. JSON MIME examples: application/json application/json; charset=UTF8 APPLICATION/JSON application/vnd.company+json "* / *" is also default to JSON- Parameters:
mime
- MIME (Multipurpose Internet Mail Extensions)- Returns:
- True if the given MIME is JSON, false otherwise.
-
selectHeaderAccept
Select the Accept header's value from the given accepts array: if JSON exists in the given array, use it; otherwise use all of them (joining into a string)- Parameters:
accepts
- The accepts array to select from- Returns:
- The Accept header to use. If the given array is empty, null will be returned (not to set the Accept header explicitly).
-
selectHeaderContentType
Select the Content-Type header's value from the given array: if JSON exists in the given array, use it; otherwise use the first one of the array.- Parameters:
contentTypes
- The Content-Type array to select from- Returns:
- The Content-Type header to use. If the given array is empty, returns null. If it matches "any", JSON will be used.
-
escapeString
-
deserialize
Deserialize response body to Java object, according to the return type and the Content-Type response header.- Type Parameters:
T
- Type- Parameters:
response
- HTTP responsereturnType
- The type of the Java object- Returns:
- The deserialized Java object
- Throws:
ApiException
- If fail to deserialize response body, i.e. cannot read response body or the Content-Type of the response is not supported.
-
serialize
Serialize the given Java object into request body according to the object's class and the request Content-Type.- Parameters:
obj
- The Java objectcontentType
- The request Content-Type- Returns:
- The serialized request body
- Throws:
ApiException
- If fail to serialize the given object
-
downloadFileFromResponse
Download file from the given response.- Parameters:
response
- An instance of the Response object- Returns:
- Downloaded file
- Throws:
ApiException
- If fail to read file content from response and write to disk
-
prepareDownloadFile
Prepare file for download- Parameters:
response
- An instance of the Response object- Returns:
- Prepared file for the download
- Throws:
IOException
- If fail to prepare file for download
-
execute
- Type Parameters:
T
- Type- Parameters:
call
- An instance of the Call object- Returns:
- ApiResponse<T>
- Throws:
ApiException
- If fail to execute the call
-
execute
Execute HTTP call and deserialize the HTTP response body into the given return type.- Type Parameters:
T
- The return type corresponding to (same with) returnType- Parameters:
call
- CallreturnType
- The return type used to deserialize HTTP response body- Returns:
- ApiResponse object containing response status, headers and data, which is a Java object deserialized from response body and would be null when returnType is null.
- Throws:
ApiException
- If fail to execute the call
-
handleResponse
Handle the given response, return the deserialized object when the response is successful.- Type Parameters:
T
- Type- Parameters:
response
- ResponsereturnType
- Return type- Returns:
- Type
- Throws:
ApiException
- If the response has an unsuccessful status code or fail to deserialize the response body
-
buildCall
public okhttp3.Call buildCall(String baseUrl, String path, String method, List<Pair> queryParams, List<Pair> collectionQueryParams, Object body, Map<String, String> headerParams, Map<String, throws ApiExceptionString> cookieParams, Map<String, Object> formParams, Set<String> authNames) Build HTTP call with the given options.- Parameters:
baseUrl
- The base URLpath
- The sub-path of the HTTP URLmethod
- The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE"queryParams
- The query parameterscollectionQueryParams
- The collection query parametersbody
- The request body objectheaderParams
- The header parameterscookieParams
- The cookie parametersformParams
- The form parametersauthNames
- The authentications to apply- Returns:
- The HTTP call
- Throws:
ApiException
- If fail to serialize the request body object
-
joinQueryParameters
-
joinQueryParameters
Joins query parameters from a Map into a StringBuilder representation.- Parameters:
sb
- The StringBuilder to append the query parameters to.params
- The Map containing the query parameters.- Returns:
- The StringBuilder representation of the joined query parameters.
-
urlEncode
-
buildTimestamp
-
buildRequest
public okhttp3.Request buildRequest(String baseUrl, String path, String method, List<Pair> queryParams, List<Pair> collectionQueryParams, Object body, Map<String, String> headerParams, Map<String, throws ApiExceptionString> cookieParams, Map<String, Object> formParams, Set<String> authNames) Build an HTTP request with the given options.- Parameters:
baseUrl
- The base URLpath
- The sub-path of the HTTP URLmethod
- The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE"queryParams
- The query parameterscollectionQueryParams
- The collection query parametersbody
- The request body objectheaderParams
- The header parameterscookieParams
- The cookie parametersformParams
- The form parametersauthNames
- The authentications to apply- Returns:
- The HTTP request
- Throws:
ApiException
- If fail to serialize the request body object
-
buildUrl
public String buildUrl(String baseUrl, String path, List<Pair> queryParams, List<Pair> collectionQueryParams) Build full URL by concatenating base path, the given sub path and query parameters.- Parameters:
baseUrl
- The base URLpath
- The sub pathqueryParams
- The query parameterscollectionQueryParams
- The collection query parameters- Returns:
- The full URL
-
processHeaderParams
-
processCookieParams
-
updateParamsForAuth
public void updateParamsForAuth(Set<String> authNames, List<Pair> queryParams, Map<String, String> headerParams, Map<String, throws ApiExceptionString> cookieParams, String payload, String method, URI uri) Update query and header parameters based on authentication settings.- Parameters:
authNames
- The authentications to applyqueryParams
- List of query parametersheaderParams
- Map of header parameterscookieParams
- Map of cookie parameterspayload
- HTTP request bodymethod
- HTTP methoduri
- URI- Throws:
ApiException
- If fails to update the parameters
-
buildRequestBodyFormEncoding
-
buildRequestBodyMultipart
-
guessContentTypeFromFile
-