2017-06-12 2 views
0

Je suis nouveau sur java et j'en ai besoin pour un projet. Je dois utiliser Apache HttpClient en combinaison avec FastBill Api.Apache httpclient avec fastbill.api en java

La commande Curl pour FastBill Api est

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 

J'ai utilisé la commande curl avec succès avec ce fichier JSON

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

Alors, je suis sûr que mon dossier nom d'utilisateur, mot de passe et JSON est travail. FastbillApi utilise l'authentification de base http. J'ai essayé en 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(); 
    } 

Comme réponse, je reçois maintenant, je

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) 

aucune idée de ce que je fais mal.

Répondre

0

J'ai trouvé une solution

Cette méthode effectue la demande. Fastbill accepte JSON ou demande XML, donc je fait un détour par le constructeur JSONString

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; 
} 

Cette méthode crée la authentificationstring pour la demande, Fastbill accepte une chaîne codée base64. Pour le projet dont je avais besoin de stocker le courrier électronique et l'API dans un fichier config.xml

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; 
} 

Cette méthode crée la chaîne JSON de mon fichier JSON demandé

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; 
} 
0

J'ai eu des problèmes similaires que j'ai réussi à résoudre en utilisant Matt S. exemple de solution pour Apache HTTP BasicScheme.authenticate deprecated?.

authentifiant par:

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);