栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot RestTemplate 发送POST请求

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot RestTemplate 发送POST请求

SpringBoot RestTemplate 发送POST请求

帮助类代码

import com.alibaba.fastjson.JSONObject;
import org.springframework.http.*;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;

public class RequestUtils {

	
	public static JSONObject sendPost(String url, MultiValueMap parameter) {
        RestTemplate client = new RestTemplate();
        client.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.valueOf("application/x-www-form-urlencoded;charset=UTF-8"));
        HttpMethod method = HttpMethod.POST;
        // 以表单的方式提交
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        // 将请求头部和参数合成一个请求
        HttpEntity> requestEntity = new HttpEntity<>(parameter, headers);
        // 执行HTTP请求,将返回的结构使用JSONObject类格式化
        ResponseEntity result = client.exchange(url, method, requestEntity, String.class);
        return JSONObject.parseObject(result.getBody());
    }
    
}

调用代码

//地址
String url = "http://localhost:8080/login/auth";
//参数
MultiValueMap params = new LinkedMultiValueMap<>();
params.add("userName", "zhangsan");
params.add("password", "123456");;
JSONObject result = StExpressUtils.sendPost(url, params);
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/975975.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号