代码
package cn.ly.blog.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
/**
* User: HZX
* Date: 2021/5/25/025
* Time: 13:34
* Description:获取票据
*/
@Component
public class GetTableuaBill {
private final static Logger LOGGER = LoggerFactory.getLogger(GetTableuaBill.class);
/**
* tableua服务器地址
*/
private static String serverAddress;
@Value("${serverAddress:NaN}")
public void setServerAddress(String serverAddress){
GetTableuaBill.serverAddress=serverAddress;
}
/**
* tableua用户名
*/
private static String name;
@Value("${name:NaN}")
public void setUserName(String name){
GetTableuaBill.name=name;
}
/**
* 信任ip
*/
private static String trustIp;
@Value("${trustIp:NaN}")
public void setTrustIp(String trustIp1){
GetTableuaBill.trustIp=trustIp1;
}
/**
* restTemplate http工具
*/
@Resource
private RestTemplate restTemplate;
private static GetTableuaBill codeMapUtils;
@PostConstruct
public void init() {
codeMapUtils = this;
codeMapUtils.restTemplate = this.restTemplate;
}
public static String getBill(){
LOGGER.info("tableua服务器地址:"+serverAddress+" tableua用户名:"+name+" tableua信任ip:"+trustIp);
// 请求头设置,x-www-form-urlencoded格式的数据
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//提交参数设置
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("username", name);
map.add("client_ip", trustIp);
// 组装请求体
HttpEntity<MultiValueMap<String, String>> request =
new HttpEntity<MultiValueMap<String, String>>(map, headers);
// 发送post请求,并打印结果,以String类型接收响应结果JSON字符串
String result = codeMapUtils.restTemplate.postForObject(serverAddress, request, String.class);
LOGGER.info("获取的票据是:"+result);
return result;
}
}