【问题标题】:Apache httpclient whith fastbill.api in javaApache httpclient 与 java 中的 fastbill.api
【发布时间】:2017-06-12 06:52:32
【问题描述】:

我是 java 新手,项目需要这个。我必须将Apache HttpClientFastBill Api 结合使用。

FastBill Api 的 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)

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

【问题讨论】:

    标签: java curl apache-httpclient-4.x


    【解决方案1】:

    我遇到过类似的问题,我通过使用 Matt S.Apache HTTP BasicScheme.authenticate deprecated? 示例解决方案设法解决了这些问题。

    认证方式:

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

    【讨论】:

      【解决方案2】:

      我找到了解决办法

      此方法执行请求。 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;
      }
      

      此方法为请求创建身份验证字符串,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;
      }
      

      【讨论】:

        猜你喜欢
        • 2011-09-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-03
        相关资源
        最近更新 更多