libcvrapi/src/main/java/biz/nellemann/libcvrapi/CvrApi.java

106 lines
2.7 KiB
Java

/*
*/
package biz.nellemann.libcvrapi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Credentials;
import com.google.gson.Gson;
public class CvrApi {
private final static Logger log = LoggerFactory.getLogger(CvrApi.class);
private final OkHttpClient client;
private final String userAgent;
private final String authenticationToken;
public CvrApi(String userAgent, String authenticationToken) {
this.userAgent = userAgent;
this.authenticationToken = authenticationToken;
client = new OkHttpClient();
}
private String get(String url) throws IOException, Exception {
String credential = Credentials.basic(authenticationToken, "");
Request request = new Request.Builder()
.url(url)
.header("User-Agent", userAgent)
.header("Authorization", credential)
.addHeader("Accept", "application/json;")
.build();
Response response = client.newCall(request).execute();
switch(response.code()) {
case 200:
return response.body().string();
case 401:
throw new Exception("Access denied");
default:
throw new Exception("Unknown error, status code: " + response.code());
}
}
/**
* https://rest.cvrapi.dk/v1/dk/company/vatNumber
*
* @param vatNumber
* @return
* @throws IOException
*/
protected String getCompanyJson(String vatNumber) throws IOException, Exception {
String response = get("https://rest.cvrapi.dk/v1/dk/company/"+vatNumber);
return response;
}
/**
* Use GSON to deserialize JSON into objects.
*
* @param json
* @return
*/
protected Company parseJsonIntoCompany(String json) {
Company company;
try {
company = new Company();
company = new Gson().fromJson(json, Company.class);
} catch (Exception e) {
log.error("Error deserializing json into Company", e);
return null;
}
return company;
}
public Company getCompanyByVatNumber(String vatNumber) {
try {
String json = getCompanyJson(vatNumber);
return parseJsonIntoCompany(json);
} catch (IOException e) {
log.error("IO Error", e);
return null;
} catch (Exception e) {
log.error("Other Error", e);
return null;
}
}
}