ResTemplate摘要认证
程序员文章站
2022-07-10 09:17:11
ResTemplate摘要认证模拟Postman Authorization下Digest Auth(摘要认证)类型的认证方式引入依赖org.apache.httpcomponents httpclient 4.5.12
ResTemplate摘要认证
模拟Postman Authorization下Digest Auth(摘要认证)类型的认证方式
- 引入依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.12</version>
</dependency>
- 工具方法代码如下:
/**
*
* @param http_url 目标API
* @param method 请求方法
* @param headers
* @param params
* @param askUsername 用户名
* @param askPwd 密码
* @param host 目标IP
* @param port 端口号
* @param clazz
* @param uriParams
* @param <T>
* @Description 摘要认证
* @return
*/
public static <T> ResponseEntity<T> getResponseEntityWithDigestAuth(String http_url, HttpMethod method,HttpHeaders headers,Object params, String askUsername, String askPwd, String host, int port,Class<T> clazz, Map<String, ?> uriParams) {
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM),
new UsernamePasswordCredentials(askUsername, askPwd));
CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpclient));
//支持中文编码
restTemplate.getMessageConverters().set(1,
new StringHttpMessageConverter(Charset.forName("UTF-8")));
MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
headers.setContentType(type);
headers.add("Accept", MediaType.APPLICATION_JSON.toString());
HttpEntity<Object> entity = new HttpEntity<>(params, headers);
return restTemplate.exchange(http_url, method, entity, clazz, uriParams);
}
- 测试类代码:
String host="127.0.0.1";
int port = 8083;
String http_url = basicUrl+askForHelpUrl+"/0";
HttpHeaders headers = new HttpHeaders();
MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
headers.setContentType(type);
headers.add("Accept", MediaType.APPLICATION_JSON.toString());
List<TaskForm> ticketList = new ArrayList<>();
ResponseEntity<Map> responseEntity = RestClient.getResponseEntityWithDigestAuth(http_url,HttpMethod.GET,headers,null,askUsername,askPwd,host,port,Map.class,new HashMap<>());
LinkedHashMap map = (LinkedHashMap) responseEntity.getBody();
本文地址:https://blog.csdn.net/qq_42026590/article/details/110229015
上一篇: 线程有哪些基本状态?
下一篇: 矩形覆盖(斐波那契)