Java -- 如何利用 RestTemplate 实现 HTTP 的 Post 和 Get 请求 & 如何在 Post 请求中加请求头

Get 请求获取 Token 示例

HttpHeaders header = new HttpHeaders();
JSONObject jsonObj = HttpHelper.sendGetRequest(url, header);
String token = jsonObj.getString("token");

Post 请求获取数据示例

HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Bearer "+ token);
JSONObject requestObj = new JSONObject();
requestObj.put("propName", "name");
requestObj.put("propValue", vmHostName);
requestObj.put("type", "HOST");
JSONObject jsonObj = HttpHelper.sendPostRequest(url,requestObj,headers);

在这里插入图片描述
请求体 Body

{"propValue":"sd2_25","type":"HOST","propName":"name"}

工具类

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;

public class HttpHelper {

	public static JSONObject sendGetRequest(String url,HttpHeaders headers){
        RestTemplate client = new RestTemplate();
        HttpMethod method = HttpMethod.GET;
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Object> entity = new HttpEntity<Object>(null, headers);
        ResponseEntity<JSONObject> result = client.exchange(url, method, entity, JSONObject.class);
        if(result.getBody().getString("code").equals("200")){
        	 return  result.getBody();
        }
        else{
        	return new JSONObject();
        }
    }
	
	public static JSONObject sendPostRequest(String url, JSONObject json, HttpHeaders headers){
        RestTemplate client = new RestTemplate();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Object> entity = new HttpEntity<Object>(json, headers);
        JSONObject result = client.postForObject(url, entity, JSONObject.class);
        if(result.getString("code").equals("200")){
        	return result;
        }
        else{
        	return new JSONObject();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值