Newer
Older
fedex-api / src / main / java / io / ljunggren / fedex / api / service / OauthService.java
@Alex Ljunggren Alex Ljunggren on 18 Aug 2025 1 KB Added rate request and address validation
package io.ljunggren.fedex.api.service;

import java.util.Arrays;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;

import io.ljunggren.fedex.api.authorization.AuthToken;

public class OauthService extends BaseService {
    
    public OauthService(String domain) {
        super(domain);
    }

    private final String URI = domain + "/oauth/token";
    
    public AuthToken authorize(String clientId, String clientSecret) throws Exception {
        return authorize(clientId, clientSecret, getHttpClient());
    }
    
    public AuthToken authorize(String clientId, String clientSecret, CloseableHttpClient httpClient) throws Exception {
        HttpPost post = new HttpPost(URI);
        List<NameValuePair> parameters = generateParameters(clientId, clientSecret);
        try {
            post.setEntity(new UrlEncodedFormEntity(parameters));
            CloseableHttpResponse response = httpClient.execute(post);
            String json = getResult(response);
            return parse(json, AuthToken.class);
        } finally {
            httpClient.close();
        }
    }
    
    private List<NameValuePair> generateParameters(String clientId, String clientSecret) {
        return Arrays.asList(new BasicNameValuePair[] {
                new BasicNameValuePair("grant_type", "client_credentials"),
                new BasicNameValuePair("client_id", clientId),
                new BasicNameValuePair("client_secret", clientSecret)
        });
    }

}