1

I'm new to java and need this for a project. I have to use Apache HttpClient in combination with FastBill Api.

The Curl command for FastBill Api is

curl -v -X POST \ 
–u {E-Mail-Adresse}:{API-Key} \ 
-H 'Content-Type: application/json' \ 
-d '{json body}' \ 
https://my.fastbill.com/api/1.0/api.php 

I used the curl command with success with this json file

{
    "SERVICE":"customer.create",
    "DATA":
    {
        "CUSTOMER_TYPE":"business",
        "ORGANIZATION":"Musterfirma",
        "LAST_NAME":"Mmann"
    }
}

So, I'm sure my username, password and json file is working. FastbillApi use http Basic Authentification. I tried this in java

public class Fastbill implements FastbillInterface  {

private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "https://my.fastbill.com/api/1.0/api.php";

public Customer createCustomer(String firstname, String lastname, CustomerType customertype, String organisation) {

    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials
     = new UsernamePasswordCredentials("*****@****", "************"); //Api Username and API-Key


    HttpClient client = HttpClientBuilder.create()
      .setDefaultCredentialsProvider(provider)
      .build();


    HttpPost httpPost = new HttpPost(URL_SECURED_BY_BASIC_AUTHENTICATION);
    httpPost.setHeader("Content-Type", "application/json");
    String json = "{\"SERVICE\":\"customer.create\",\"DATA\":{\"CUSTOMER_TYPE\":\"business\",\"ORGANIZATION\":\"Musterfirma\",\"LAST_NAME\":\"Newmann\"}}";
    try {
        HttpEntity entity = new ByteArrayEntity(json.getBytes("UTF-8"));
        httpPost.setEntity(entity);
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    HttpResponse response;
    try {           
        response = client.execute(httpPost);
        int statusCode = response.getStatusLine()
                  .getStatusCode();
        System.out.println(statusCode);
        String responseString = new BasicResponseHandler().handleResponse(response);
        System.out.println(responseString);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }catch (Exception e){
        e.printStackTrace();
    }

As response I get

org.apache.http.client.HttpResponseException: Unauthorized
at org.apache.http.impl.client.AbstractResponseHandler.handleResponse(AbstractResponseHandler.java:70)
at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:66)
at fastbillAPI.Fastbill.createCustomer(Fastbill.java:93)
at main.Mar.main(Mar.java:38)

Now, I have no clue what I'm doing wrong.

Jens
  • 67,715
  • 15
  • 98
  • 113
des_viech
  • 29
  • 6

2 Answers2

1

I've had similar issues that I managed to resolve by using Matt S. example solution for Apache HTTP BasicScheme.authenticate deprecated?.

Authenticating via:

UsernamePasswordCredentials creds = new UsernamePasswordCredentials("admin", "admin");
URI uriLogin = URI.create("http://localhost:8161/hawtio/auth/login/");
HttpPost hpPost = new HttpPost(uriLogin);
Header header = new BasicScheme(StandardCharsets.UTF_8).authenticate(creds , hpPost, null);
hpPost.addHeader( header); 
Rido
  • 11
  • 1
1

I found a solution

This method performs the Request. Fastbill accepts either JSON or XML Request, so I made a detour with the JSONString builder

private String performFastbillRequest(String InputJsonRequest) {
    String responseString = null;

    CloseableHttpClient client = HttpClients.createDefault();
    try {
        URI uri = URI.create(URL_SECURED_BY_BASIC_AUTHENTICATION);
        HttpPost post = new HttpPost(uri);
        String auth = getAuthentificationString();

        post.addHeader("Content-Type", "application/json");
        post.addHeader("Authorization", auth);

        StringEntity stringEntity = new StringEntity(InputJsonRequest);
        post.setEntity(stringEntity);

        CloseableHttpResponse response = client.execute(post);

        HttpEntity entity = response.getEntity();
        responseString = EntityUtils.toString(entity, "UTF-8");
   } catch (Exception e) {
       e.printStackTrace();
   }
   return responseString;
}

This Method creates the authentificationstring for the request, Fastbill accepts a base64 encoded string. For the project I needed to store the email and the API in an config.xml file

private String getAuthentificationString() {
    String authentificationString = "Basic ";
    String fastbillUsernameAndApiKey = null;
    XmlParser getFromXml = new XmlParser();
    fastbillUsernameAndApiKey = getFromXml.getApiEmailFromConfigFile() + ":" + getFromXml.getApiKeyFromConfigFile();
    //if email and apikey are not stored in config.xml you need following string containing the emailadress and ApiKey seperated with ':'
    //f.ex. fastbillUsernameAndApiKey = "*****@****.***:*********";
    authentificationString = authentificationString + base64Encoder(fastbillUsernameAndApiKey);   
    return authentificationString;
}

private String base64Encoder(String input) {
    String result = null;
    byte[] encodedBytes = Base64.encodeBase64(input.getBytes());
    result = new String(encodedBytes);
    return result;
}

This method creates the JSON string from my requested JSON file

private String createCustomerJson(String firstname,
  String lastname) {
      String createCustomerJsonStringBuilder = "{\"SERVICE\":\"customer.create\",\"DATA\":{\"CUSTOMER_TYPE\":\"";
    createCustomerJsonStringBuilder += "consumer";
    createCustomerJsonStringBuilder += /* "\", */"\"LAST_NAME\":\"";
    createCustomerJsonStringBuilder += lastname;
    createCustomerJsonStringBuilder += "\",\"FIRST_NAME\":\"";
    createCustomerJsonStringBuilder += firstname;
    createCustomerJsonStringBuilder += "\"}}";

    return createCustomerJsonStringBuilder;
}
des_viech
  • 29
  • 6