Java中发起http的几种方式

**方式一 **

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
 // 创建一个RestTemplate对象,用来发起http请求
RestTemplate restTemplate =new RestTemplate();
// 创建一个RequestEntity对象,指定了请求的URL、设置请求体的格式为JSON、并设置了请求体
RequestEntity<String> tokenRequest = RequestEntity.post(URI.create(jwInfo.getTokenUrl()))
.contentType(MediaType.APPLICATION_JSON)
.body("{\"userId\":\""+jwInfo.getTokenAppId()+"\",\"password\":\""+jwInfo.getTokenAppKey()+"\"}");
// 发起请求并接收响应,包含了HTTP响应的状态码、响应头和响应体(已被转换为字符串)
ResponseEntity<String> exchange = restTemplate.exchange(tokenRequest, String.class);
// 解析出响应体
JSONObject jsonA = JSONObject.parseObject(exchange.getBody());
// 响应成功
if (jsonA.get("code").toString().equals("200")) {
// 获取响应体中的数据
JSONObject jsonB = JSONObject.parseObject(jsonA.get("data").toString());
// 如果 jsonB 包含数据,则使用jwInfo.getIndexUrl()作为基础URL并附加从jsonB中获取的token字段的值来构造一个新的URL tmpUrl
if (!jsonB.isEmpty()) {
String tmpUrl = jwInfo.getIndexUrl() + jsonB.get("token").toString();
if(isNewTab!=null && isNewTab.equals("1")){
// 如果变量 isNewTab 不为 null 并且等于字符串 "1",则打开一个新的浏览器标签页并导航到 tmpUrl
response.getWriter().print("<script>window.open('" + tmpUrl + "','_blank')</script>" );
} else {
// 否则重定向到tmpUrl
response.sendRedirect(tmpUrl);
}
}
}

Java中发起http的几种方式
https://lzhengjy.github.io/2024/09/16/Java中发起http的几种方式/
作者
Zheng
发布于
2024年9月16日
许可协议