java中带有fastbill.api的Apache httpclient

java中带有fastbill.api的Apache httpclient,java,curl,apache-httpclient-4.x,Java,Curl,Apache Httpclient 4.x,我是java新手,在项目中需要这个。我必须结合使用 fastbillapi的Curl命令是 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 我在这个json文件中成功地使用了curl命令 { "SERVICE":"customer.c

我是java新手,在项目中需要这个。我必须结合使用

fastbillapi的Curl命令是

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 
我在这个json文件中成功地使用了curl命令

{
    "SERVICE":"customer.create",
    "DATA":
    {
        "CUSTOMER_TYPE":"business",
        "ORGANIZATION":"Musterfirma",
        "LAST_NAME":"Mmann"
    }
}
所以,我确信我的用户名、密码和json文件都正常工作。FastbillApi使用http基本身份验证。我用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();
    }
我得到的答复是

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)

现在,我不知道我做错了什么。

我遇到过类似的问题,我通过使用示例解决方案解决了这些问题

通过以下方式进行身份验证:

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); 
我找到了解决办法

此方法执行请求。Fastbill接受JSON或XML请求,因此我绕道使用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;
}
此方法为请求创建authentificationstring,Fastbill接受base64编码的字符串。对于这个项目,我需要将电子邮件和API存储在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;
}
此方法从我请求的JSON文件创建JSON字符串

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