【发布时间】:2017-06-12 06:52:32
【问题描述】:
我是 java 新手,项目需要这个。我必须将Apache HttpClient 与FastBill 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