【HTTP】使用 RestTemplete 实现 post请求_java

【HTTP】使用 RestTemplete 实现 post请求_post_02

如上图,要求:

  1. post请求;
  2. x-www-form-urlencoded 类型;

如下代码没有进行整理,但是测试OK

package com.chinamobile.epic.http;

import com.chinamobile.epic.model.GraphiteResultModel;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.List;

public class RestTempleteTest {
public static void main(String[] args) throws IOException {
RestTemplate restTemplate = new RestTemplate();

String endpoint = "http://10.254.3.92:5001/render";
String target = "YFQ.vm.{0003d969-3fde-432f-898a-09456e5527af,002badb2-79ae-43e3-9dea-9618edea6b54}.cpu.cpu.percent.util";
String format = "json";
String from = "-10min";
String until = "now";

System.out.println("=================================================");
// 设置请求体参数
MultiValueMap<String, String> bodyMap = new LinkedMultiValueMap<String, String>();
bodyMap.add("target", target);
bodyMap.add("format", format);
bodyMap.add("from", from);
bodyMap.add("until", until);

// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(bodyMap, headers);

//进行HTTP请求
ResponseEntity<String> model = restTemplate.exchange(endpoint, HttpMethod.POST, request, String.class);
String response = model.getBody();

// 转换请求结果
ObjectMapper mapper = new ObjectMapper();
List<GraphiteResultModel> graphiteResultModels = mapper.readValue(response, new TypeReference<List<GraphiteResultModel>>() {
});

System.out.println("================");
System.out.println(graphiteResultModels.toString());
}

}

转换结果的类

package com.chinamobile.epic.model;

import com.google.common.base.Splitter;
import org.springframework.util.CollectionUtils;

import java.util.List;

public class GraphiteResultModel {
private String target; //示例:summarize(clm.pm.10_144_202_142.agg.cpu.percent-avg.system,'10min','avg',true)
private List<List<Object>> datapoints;

public String getTarget() {
return target;
}

public void setTarget(String target) {
this.target = target;
}

public List<List<Object>> getDatapoints() {
return datapoints;
}

public void setDatapoints(List<List<Object>> datapoints) {
this.datapoints = datapoints;
}

}