java RestTemplate post请求加json参数

java RestTemplate post请求加json参数 的两种方法

public String geturl() throws Exception {


        CommonResult commonResult = new CommonResult();
        try {
            RestTemplate restTemplate = new RestTemplate(generateHttpRequestFactory());


            JSONObject json=new JSONObject();
            json.put("username",username);
            json.put("password",password);


            Map<String, String > heads = new HashMap<>();
            heads.put("Content-Type", "application/json;charset=UTF-8");
            HttpResponse httpResponse =  HttpRequest.post(url+"/login") // url
                    .headerMap(heads, false) // 请求头设置
                    .body(json.toJSONString()) // json参数
                    .timeout(5 * 60 * 1000) // 超时
                    .execute(); // 请求
            System.out.println("获取返回服务器的状态码:----- " + httpResponse.getStatus() );
            System.out.println("获取返回服务器的状态码:----- " + httpResponse );



            Map<String, String> requestBody = new HashMap<>();
            requestBody.put("username",username);
            requestBody.put("password",password);
            HttpHeaders requestHeaders = new HttpHeaders();
            // 重点是配置请求头内容类型为:"application/json"
            requestHeaders.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<Map<String, String>> r = new HttpEntity<>(requestBody, requestHeaders);
            String data= restTemplate.postForObject(url+"/login", r, String.class);

            System.out.println(data);





  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值