對接第三方廣告平台 API,需使用 HTTP Basic Auth 進行身份驗證,通過 POST 提交表單數據創建創意素材。採用 Apache HttpComponents Client 4.x 實現。
import org.apache.http.*;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.http.auth.*;
import java.util.*;
public class CreativeApiClient {
private static final String BASE_URL = PropertiesLoader.getProperty("ALLYES_SERVER");
private static final String USERNAME = PropertiesLoader.getProperty("ALLYES_USERNAME");
private static final String PASSWORD = PropertiesLoader.getProperty("ALLYES_PASSWORD");
public static Map<String, Object> addCreative(CreativeAudit audit) {
Map<String, Object> result = new HashMap<>();
String endpoint = BASE_URL + "/creatives/add";
// 1. 構建 HttpClient 並配置 Basic Auth
DefaultHttpClient httpClient = new DefaultHttpClient();
httpClient.getCredentialsProvider().setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials(USERNAME, PASSWORD)
);
try {
// 2. 準備 POST 表單參數
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("name", audit.getName()));
params.add(new BasicNameValuePair("width", String.valueOf(audit.getWidth())));
params.add(new BasicNameValuePair("height", String.valueOf(audit.getHeight())));
// 根據文件後綴判斷素材類型
String type = "9"; // 圖片默認
String path = audit.getRelative_path().toLowerCase();
if (path.endsWith(".gif")) type = "10";
else if (path.endsWith(".swf")) type = "11";
params.add(new BasicNameValuePair("type", type));
params.add(new BasicNameValuePair("creativeTagId", audit.getAdCategory().getAd_caterory().substring(2)));
params.add(new BasicNameValuePair("code", audit.getCode()));
params.add(new BasicNameValuePair("bindId", audit.getGeoid()));
// 3. 發送請求
HttpPost post = new HttpPost(endpoint);
post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse response = httpClient.execute(post);
int status = response.getStatusLine().getStatusCode();
String body = EntityUtils.toString(response.getEntity(), "UTF-8");
// 4. 統一結果封裝
if (status == HttpStatus.SC_OK) {
JSONObject json = JSONObject.fromObject(body);
audit.setUuid(json.getString("id"));
result.put("success", audit);
} else {
result.put("failed", String.format("創意 %s 創建失敗, HTTP %d: %s",
audit.getGeoid(), status, body));
}
} catch (Exception e) {
e.printStackTrace();
result.put("failed", "提交數據異常: " + e.getMessage());
} finally {
httpClient.getConnectionManager().shutdown(); // 釋放連接資源
}
return result;
}
}
HttpClient 內部自動在請求頭添加:
Authorization: Basic base64(username:password)
AuthScope.ANY 表示對所有主機/端口/域 使用同一憑證,生產環境建議縮小範圍:
new AuthScope("api.example.com", 443, AuthScope.ANY_REALM)
UrlEncodedFormEntity 自動設置 Content-Type: application/x-www-form-urlencoded; charset=UTF-8HttpEntity 內容(即使失敗),否則連接無法釋放回池EntityUtils.toString(entity, "UTF-8") 避免編碼問題Map<String, Object> 封裝成功/失敗,上層調用者無需捕獲異常| 4.x (Legacy) | 5.x (Modern) |
|---|---|
DefaultHttpClient | HttpClients.createDefault() |
HttpPost | HttpPost (同包不同實現) |
UrlEncodedFormEntity | UrlEncodedFormEntity |
BasicNameValuePair | BasicNameValuePair |
EntityUtils.toString() | EntityUtils.toString() |
UsernamePasswordCredentials | UsernamePasswordCredentials |
| 連接管理手動 shutdown | 實現 Closeable,try-with-resources 自動關閉 |
PoolingHttpClientConnectionManager 限制最大連接數、每路由連接數RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(15000)HttpRequestRetryHandler,針對冪等請求自動重試SSLContext 信任自簽證書或內網 CAApache HttpClient 配合 UsernamePasswordCredentials 實現 Basic Auth 极其簡潔。關鍵在於統一異常處理、資源釋放、響應體讀取、編碼指定四個工程細節。遷移至 5.x 版本可獲得更好的模塊化、響應式支援與記憶體效率。