ResponseEntity<String> resultMap = restTemplate.getForEntity

使用restTemplate的get方法获取返回值中的头部信息的 cookie,吧cookie拿来放到头部作为参数再次请求另一个接口,就是先登录获取返回的cookie 吧cookie作为参数调用另一个接口。。。。。

 @RequestMapping(value = "/login")
    @ResponseBody
    public String login(String code) throws Exception {
        String username="123";
        String password = "123";

        try {
            RestTemplate restTemplate = new RestTemplate(generateHttpRequestFactory());
            ResponseEntity<String> resultMap = restTemplate.getForEntity("http://123/api/user/login?username=" + username+"&password="+password, String.class);
            JSONObject jsonObject = JSONObject.parseObject(resultMap.getBody());

            if("success".equals(jsonObject.get("msg"))&&resultMap.getHeaders().get("Set-Cookie").size()>0){
               String Cookie = resultMap.getHeaders().get("Set-Cookie").get(0).split(";")[0];
                HttpHeaders headers = new HttpHeaders();
                headers.put(HttpHeaders.COOKIE, Collections.singletonList(Cookie));
                HttpEntity<String> requestEntity = new HttpEntity<String>(headers);

                ResponseEntity<String> resultMap1 = restTemplate.exchange("http://123/"+code+"/"+code , HttpMethod.GET, requestEntity, String.class);
                resultMap1.getBody();
               return Cookie;
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
            return null;
        }
        return null;
    }

参考代码A

Map<String,Object> params=new HashMap<>();
params.put("username",username);
params.put("password",password);
ResponseEntity<String> entity = restTemplate.postForEntity(loginUrl, params, String.class);
List<String> cookies = entity.getHeaders().get("Set-Cookie");

//        log.info(message);
HttpHeaders headers = new HttpHeaders();
/* 登录获取Cookie 这里是直接给Cookie,可使用下方的login方法拿到Cookie给入*/
headers.put(HttpHeaders.COOKIE,cookies);        //将cookie存入头部
HttpEntity<String> requestEntity = new HttpEntity<String>(headers);

String body = restTemplate.exchange(hostUrl+map.get("yyId"), HttpMethod.GET, requestEntity, String.class).getBody();
log.info(body);

参考代码B

package com.xinghuo.controller;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
 
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
 
/**
 * 测试restTemplate
 */
@RestController
@Api(tags = "测试")
@RequestMapping("/test")
public class HttpController{
    
    @Autowired
    private RestTemplate restTemplate;
    
    /**
     * 测试
     */
    @RequestMapping(value = "/http", method = RequestMethod.GET)
    @ApiOperation(value = "测试http")
    public String http() {
        String id = "52db70d13ad74b0f85142e39b32164b4";
        String name = "测试";
        //参数
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<String, Object>();
        param.add("id", id);
        param.add("name", name);
        
        //请求头
        HttpHeaders headers = new HttpHeaders();
        headers.add("accessToken", "3d40e41e9d764d30a9a4d72e61ad61b9");
        
        //封装请求头
        HttpEntity<MultiValueMap<String, Object>> formEntity = new HttpEntity<MultiValueMap<String, Object>>(headers);
        
        try {
            //访问地址
            String url = "http://localhost:8080/testservice/test/get";
            
            //1. 有参数,没有请求头,拼接方式
            String result1 = restTemplate.getForObject(url + "?id="+id+"&name="+name, String.class);
            //2. 有参数,没有请求头,占位符方式
            String result2 = restTemplate.getForObject(url + "?id={id}&name={name}", String.class, param);
            //3. 有请求头,没参数,result3.getBody()获取响应参数
            ResponseEntity<String> result3 = restTemplate.exchange(url, HttpMethod.GET, formEntity, String.class);
            //4. 有请求头,有参数,result4.getBody()获取响应参数
            ResponseEntity<String> result4 = restTemplate.exchange(url+"?id="+id+"&name="+name, HttpMethod.GET, formEntity, String.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }
}


以上代码存在以下问题: 1. 缺少请求体参数:在发送 POST 请求时,需要将用户名、密码和角色ID作为请求体参数发送到服务器。可以使用`MultiValueMap`对象或者自定义的DTO对象来封装这些参数。 2. 缺少请求头设置:在发送 HTTPS 请求时,需要设置相应的安全协议、证书验证等请求头信息。可以通过创建`HttpHeaders`对象,并设置相应的请求头参数来实现。 3. 缺少异常处理:在网络请求中可能会出现异常,例如连接超时、请求被拒绝等情况。可以使用`try-catch`语句来捕获异常,并进行相应的处理。 4. 缺少登录结果处理:登录成功后,需要对返回的登录结果进行处理。可以根据登录结果中的信息进行相应的逻辑操作,如跳转到首页或者提示登录失败。 修改后的代码如下: ```java public String login(String username, String password, Byte roleId) { try { // 创建请求体参数 MultiValueMap<String, Object> requestBody = new LinkedMultiValueMap<>(); requestBody.add("username", username); requestBody.add("password", password); requestBody.add("roleId", roleId); // 创建请求头设置 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); // 创建请求实体对象 HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers); // 发送 POST 请求 ResponseEntity<String> responseEntity = restTemplate.exchange("https://localhost/login/", HttpMethod.POST, requestEntity, String.class); String result = responseEntity.getBody(); // 处理登录结果 // TODO: 根据登录结果进行相应的逻辑操作 return result; } catch (Exception e) { // 处理异常 e.printStackTrace(); // TODO: 返回异常信息或进行相应的异常处理 return null; } } ``` 请注意,以上代码仅提供了一个基础的实现示例,具体的实现方式还需要根据实际情况进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值