[英]java HttpClient 403 forbidden problem?
我使用 HttpClient api 對 web 站點進行身份驗證:
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(AuthScope.ANY_HOST, 443),
new UsernamePasswordCredentials(args[0], args[1]));
HttpGet httpget = new HttpGet("http://..........");
HttpResponse response = httpclient.execute(httpget);
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: "
+ entity.getContentLength());
}
我有這個答案:
HTTP/1.1 403 Forbidden
Response content length: -1
但是使用瀏覽器,我可以使用相同的登錄名和密碼訪問此頁面!!!!
我該如何解決這個問題?
您構建 AuthScope object 並將端口參數設置為 443(HTTPS 的默認端口)。 但是,您創建了 HttpGet object,其中 URL 指向 HTTP(默認端口為 80)。
嘗試使用以下方法構建 AuthScope:
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT)
或確保端口匹配。
檢查您使用的HttpClient
版本是否是導致403
的原因。
嘗試
HttpClient httpClient = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.build();
您需要仔細查看瀏覽器實際上是如何進行身份驗證的。
您要做的是(我認為)使用 HTTP 基本身份驗證發送憑據。 如果站點設置為僅允許基於表單的身份驗證和 session cookie,那么它將忽略包含憑據的 header。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.