http请求使用 RestTemplate 发送 post 请求传递参数

http使用 RestTemplate 发送 post 请求传递参数

代码参考如下

import com.wondersgroup.yilian.interface_monitor_portallogin.entity.ResponseEntity;
import com.alibaba.fastjson.JSONObject;
import com.wondersgroup.yilian.interface_monitor_portallogin.service.PortalloginService;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;


@Service
public class PortalloginServiceImpl implements PortalloginService {
    @Override
    public ResponseEntity validateLogin(JSONObject request) {
        ResponseEntity response = new ResponseEntity();
        String code = "-1";
        String msg = "接口异常";

        //传参   入参为jeson格式
        // 格式为  request        {"username":"zhulaosan","password":"zls000000"} 
        //         head           {"type":"PATINET"}
        MultiValueMap postParameters = new LinkedMultiValueMap<>();
        String request1 = "{\"username\":\"" + request.getString("loginname") + "\",\"password\":\"" + request.getString("password") + "\"}";
        postParameters.add("request", request1); 
        postParameters.add("head", "{\"type\":\"PATINET\"}");      

        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/x-www-form-urlencoded");

        //获取当前页面状态码
        HttpEntity> r = new HttpEntity>(postParameters, headers);
        RestOperations restTemplate = new RestTemplate();
        org.springframework.http.ResponseEntity responseEntity = restTemplate.exchange("http://10.141.223.7/app_healthAttestation/healthAttestationTokenServer/getToken", HttpMethod.POST, r, String.class);
        HttpStatus status = responseEntity.getStatusCode();
        //System.out.println("status--------------------------------------->"+status);
        String srt = status.toString();
        
        //判断当前页面状态码
        if (srt.contains("200")) {

            //获取返回的数据
            String data = restTemplate.postForObject("http://10.141.223.7/app_healthAttestation/healthAttestationTokenServer/getToken", r, String.class);
            JSONObject json = JSONObject.parseObject(data);
            if (json != null) {
                if (json.get("code").equals(0)) {
                    code = "1";
                    msg = "登录成功";
                }
                if (json.get("code").equals(200)) {
                    code = "0";
                    msg = "用户名和密码错误";
                }
            }
        }

        response.setCode(code);
        response.setMsg(msg);

        return response;
    }
}

以上

你可能感兴趣的:(http请求使用 RestTemplate 发送 post 请求传递参数)