原创

RestTemplate实现post/get,设置header以及form-data传参方式

温馨提示:
本文最后更新于 2023年06月25日,已超过 356 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我

RestTemplate实现get/POST请求,设置请求头header及传参方式

package cn.92cyx.controller;
 
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.client.RestTemplate;
 
public class HttpUtil{    //传参+header(token)
    public String sendHttpGet(String id,String name,String token,String url) {        RestTemplate restTemplate = new RestTemplate();
    
        //参数
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<String, Object>();
        param.add("id", id);
        param.add("name", name);
        
        //请求头
        HttpHeaders headers = new HttpHeaders();    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE);
        headers.add("token", token);
        
        //封装请求头
        HttpEntity<MultiValueMap<String, Object>> formEntity = new HttpEntity<MultiValueMap<String, Object>>(headers);
        
        try {
            //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 "result*";
    }  //form-data 传参
  public String sendHttpPost(Map<String,String> map, String strURL){
	HttpHeaders headers = new HttpHeaders();
	MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE);
	//headers.add("Content-Type", "multipart/form-data");
	//设置参数到请求对象中
        for(String key : map.keySet()){
           param .add(key, map.get(key));
        }
		
	HttpEntity<MultiValueMap<String, Object>> requestParams = new HttpEntity<>(param, headers);
	ResponseEntity<String> response = restTemplate.postForEntity(apiUrl,requestParams,String.class);
	String result =response.getBody();
	return result;
    }}






正文到此结束
该篇文章的评论功能已被站长关闭
本文目录