gpt4 book ai didi

java - 使用 RestTemplate (3.1) 的基本身份验证

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:06:06 26 4
gpt4 key购买 nike

我正在尝试使用 Java 重现以下 curl 命令:

curl -v -u user:pass http://myapp.com/api

此命令返回一些 JSON 数据。

我的错误 Java 实现如下:

@Test
public void callTest() {
RestTemplate restTemplate = createRestTemplate("user", "pass");
URI uri = new URI("http://myapp.com/api");
String res = restTemplate.getForObject(uri, String.class);
}

private static RestTemplate createRestTemplate(String username, String password) {

UsernamePasswordCredentials cred = new UsernamePasswordCredentials(username, password);
BasicCredentialsProvider cp = new BasicCredentialsProvider();
cp.setCredentials(AuthScope.ANY, cred);
DefaultHttpClient client = new DefaultHttpClient();
client.setCredentialsProvider(cp);
ClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(client);

RestTemplate restTemplate = new RestTemplate(factory);
// set the media types properly
return restTemplate;
}

然而,当我执行测试时,它返回一个 org.springframework.web.client.HttpClientErrorException: 401 Unauthorized 异常。

登录 DEBUG 时,我看不到有关身份验证的信息...

我在设置身份验证凭据时做错了什么?

最佳答案

实例化使用

HttpClient client = new HttpClient();

不再存在,版本 4.3 中的 HttpComponents HttpClient 已弃用 DefaultHttpClient 类。因此其他答案无效或已弃用。这是我的版本,我为需要基本身份验证的其余请求编写了此类:

import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClients;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

public class RestClient extends RestTemplate {
public RestClient(String username, String password) {
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(null, -1),
new UsernamePasswordCredentials(username, password));
HttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient));
}
}

然后像这样使用它,例如:

RestClient restClient = new RestClient("username", "password");

String result = restClient.postForObject(...

关于java - 使用 RestTemplate (3.1) 的基本身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14383240/

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