使用 Apache HttpClient 在 Android 獲取驗證碼圖片(ValidateCode.aspx)時,若直接將回應實體轉為位元組陣列解碼 Bitmap,卻得到亂碼或無法顯示,通常是回應內容非圖片(如 HTML 錯誤頁、重導向頁)或編碼處理錯誤。
HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build()。DefaultHttpClient 實例(或共用 CookieStore)。EntityUtils.toByteArray() 仍會轉換,導致 BitmapFactory.decodeByteArray 失敗或產生噪點圖。// 共用 HttpClient 與 CookieStore
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
CookieStore cookieStore = new BasicCookieStore();
localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
// 1. 獲取驗證碼
HttpGet getCode = new HttpGet("https://jwgl.gxufe.cn/jwweb/sys/ValidateCode.aspx");
HttpResponse resp = httpClient.execute(getCode, localContext);
int status = resp.getStatusLine().getStatusCode();
if (status == 200) {
Header contentType = resp.getFirstHeader("Content-Type");
if (contentType != null && contentType.getValue().startsWith("image/")) {
byte[] bytes = EntityUtils.toByteArray(resp.getEntity());
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
// 更新 UI 顯示 bitmap
} else {
// 非圖片內容,記錄錯誤
String html = EntityUtils.toString(resp.getEntity());
Log.e("CAPTCHA", "非圖片回應: " + html);
}
}
// 2. 後續登入請求使用同樣 httpClient 與 localContext
HttpPost loginPost = new HttpPost("https://jwgl.gxufe.cn/jwweb/sys/login.aspx");
// ... 設定參數並執行
HttpClient + HttpContext 維持 Cookie。Content-Type 確認為 image/* 再解碼。