gpt4 book ai didi

Java - HttpClient 库的 Http 身份验证 401 错误

转载 作者:行者123 更新时间:2023-11-29 05:29:14 34 4
gpt4 key购买 nike

login window

当我尝试从网络浏览器(IE、Chromw 等)登录时出现此对话框。

使用 Apache httpclient 库尝试自动登录。

方式一. http://userid:pass@hostname (X)

方式二.使用Apache HttpClient快速入门示例(十)

以上方法都不行。

请帮助我。

最近的尝试代码

    DefaultHttpClient httpClient = new DefaultHttpClient();
try{
httpClient.getCredentialsProvider()
.setCredentials(new AuthScope(
new HttpHost(host)),
new UsernamePasswordCredentials(username, password));
HttpGet httpget = new HttpGet(host);
System.out.println("executing request" + httpget.getRequestLine());
HttpResponse response = httpClient.execute(httpget);
HttpEntity entity = response.getEntity();

System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpClient.getConnectionManager().shutdown();
}

控制台窗口显示:

'executing requestGET http://192.168.100.129/tag/unsubscribe HTTP/1.1'
'----------------------------------------'
'HTTP/1.0 401 Unauthorized'
'Response content length: 0'

最佳答案

此代码对我有用。

Base64 (apache-commons-codec) 出现的主要问题。因此,我将该 Base64 编码器更改为 sun.misc.BASE64EnCoder,它就像变魔术一样工作。

最新工作代码。

String enc = username + ":" + password;

DefaultHttpClient client = new DefaultHttpClient();
HttpResponse httpResponse;
HttpEntity entity;
HttpGet request = new HttpGet(host);

if(checkUserInfo()){
request.addHeader("Authorization", "Basic " + new BASE64Encoder().encode(enc.getBytes()));
httpResponse = client.execute(request);
entity = httpResponse.getEntity();
System.out.println(httpResponse.getStatusLine());
}else if(!checkUserInfo()){
throw new Exception("Error :: Must Call setUserInfo(String username, String password) methode firstly.");
}

控制台窗口最后说:

HTTP/1.0 200 OK

关于Java - HttpClient 库的 Http 身份验证 401 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21696651/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com