我正在尋找使用名爲HookTheory的API。我使用Java進行HTTPS調用,並且自從我第一次使用HTTP或HTTPS客戶端以來,我遇到了幾個障礙。使用HTTPS到Java中的API的身份驗證請求
Here are the document's details on User Authentication:
You authenticate to the Hooktheory API by providing an HTTP Bearer Token, according to the OAuth 2 protocol. Your HTTP Bearer Token is retrieved through the API with your www.hooktheory.com username and password. To retrieve your HTTP Bearer Token, make the following request:
POST users/auth
The body of the request must contain your www.hooktheory.com username and password:
{
"username": "Hooktheory",
"password": ""
}
The response will contain three fields, as shown below:
{
"id": 1234,
"username": "Hooktheory",
"activkey": "aoa6jjacz34kcta3aomeqwuz89"
}
The "activkey" property contains your HTTP Bearer Token; include it as an authorization header in all future requests to the API.
有人能更好地詳細講解我如何將着手在Java中這樣做呢? 簡化版代碼如下:
String url = "https://api.hooktheory.com/v1/users/auth";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add request header
con.setRequestMethod("POST");
con.setRequestProperty("username", username);
con.setRequestProperty("password", password);
String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
此代碼基本上是一個copy of the code here。
當我運行上面的後代碼時,出現401錯誤(身份驗證)。我猜測它是因爲我沒有正確格式化get/post請求。
有人可以點我在正確的方向?
哇,謝謝。這是我需要的。我不確定如何將用戶名和密碼放在那裏。我會嘗試把這個放在一起,謝謝! 我會使用類似的代碼到我原來的帖子來閱讀迴應? – Django