本範例封裝一個可重用的 APIHttpClient 類別,基於 Apache HttpClient 4.x 實現 HTTP POST 請求,支援 JSON 參數傳遞、回應狀態碼檢查、請求耗時統計、錯誤碼分類(成功、方法失敗、協議錯誤、網絡錯誤)以及詳細日誌記錄(使用 Commons Logging)。
DefaultHttpClient 與 HttpPost 實例。post(String parameters) 專注於發送請求並返回回應主體字串。getStatus() 返回 0=成功、1=方法失敗、2=協議錯誤、3=網絡錯誤,方便呼叫端判斷。EntityUtils.toString() 讀取回應實體,確保連接釋放。public class APIHttpClient {
private final String apiURL;
private final HttpClient httpClient;
private final HttpPost method;
private final Log logger = LogFactory.getLog(APIHttpClient.class);
private int status = 0; // 0 成功, 1 方法失敗, 2 協議錯誤, 3 網絡錯誤
public APIHttpClient(String url) {
this.apiURL = url;
this.httpClient = new DefaultHttpClient();
this.method = new HttpPost(apiURL);
}
public String post(String parameters) {
String body = null;
if (method != null && parameters != null && !parameters.trim().isEmpty()) {
logger.info("請求參數: " + parameters);
try {
// 將 JSON 字串包裝為表單欄位 data
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("data", parameters));
method.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
long start = System.currentTimeMillis();
HttpResponse response = httpClient.execute(method);
long end = System.currentTimeMillis();
int statusCode = response.getStatusLine().getStatusCode();
logger.info("HTTP 狀態碼: " + statusCode);
logger.info("請求耗時 (ms): " + (end - start));
if (statusCode != HttpStatus.SC_OK) {
logger.error("請求失敗: " + response.getStatusLine());
status = 1;
}
body = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
logger.error("網絡異常: " + ExceptionUtils.getFullStackTrace(e));
status = 3;
} finally {
logger.info("介面呼叫狀態碼: " + status);
}
}
return body;
}
public int getStatus() { return status; }
// 其他 getter 略...
}
APIHttpClient client = new APIHttpClient("https://api.example.com/endpoint");
String jsonParam = "[{\"id\":1,\"name\":\"test\"}]";
String response = client.post(jsonParam);
if (client.getStatus() == 0) {
System.out.println("回應: " + response);
} else {
System.err.println("呼叫失敗,狀態碼: " + client.getStatus());
}
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
data 傳送,實際 API 若要求直接發送 JSON 主體,請改用 StringEntity 並設定 Content-Type: application/json。DefaultHttpClient 在 HttpClient 4.3+ 已棄用,建議改用 HttpClientBuilder.create().build()。