在Java中,調用第三方接口通常是通過HTTP客戶端庫實現的。這里以Apache HttpClient為例,演示如何調用第三方接口。
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class ThirdPartyApiCall {
public static void main(String[] args) {
String apiUrl = "https://api.example.com/data";
try {
String response = callThirdPartyApi(apiUrl);
System.out.println("Response: " + response);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String callThirdPartyApi(String apiUrl) throws Exception {
// 創建一個可關閉的HTTP客戶端
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// 創建一個HttpGet對象,指定API URL
HttpGet httpGet = new HttpGet(apiUrl);
// 執行GET請求
try (HttpResponse httpResponse = httpClient.execute(httpGet)) {
// 獲取響應實體
HttpEntity httpEntity = httpResponse.getEntity();
// 將響應實體轉換為字符串
if (httpEntity != null) {
String responseString = EntityUtils.toString(httpEntity, "UTF-8");
return responseString;
}
}
}
// 如果發生異常,拋出異常
throw new Exception("Failed to call third-party API.");
}
}
在這個示例中,我們首先創建了一個可關閉的HTTP客戶端,然后創建了一個HttpGet對象并指定API URL。接著,我們執行GET請求并獲取響應實體。最后,我們將響應實體轉換為字符串并返回。
注意:在實際項目中,你可能需要處理更多的細節,例如異常處理、請求頭設置、POST請求等。這個示例僅用于演示基本的調用過程。