前言
spring boot resttemplate使用get请求,请求头header的设置及传参方式
- 1. 有参数,没有请求头
- 2. 有请求头,没参数
- 3. 有请求头,有参数
resttemplate
代码如下:
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";
}
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论