HTTP请求通用Restful风格工具类
一、创建测试方法
/**
* 模拟请求his测试类
*
* @Author: DengChang
* @Date: 2020/8/25 11:07
*/
@RestController
@RequestMapping("rest")
@Api (tags = "测试接口")
public class HttpRestController {
@Autowired
private HttpRestUtil httpRestUtil;
/**
* 登录质控测试post请求
*
* @return
*/
@ApiOperation (value = "登录质控测试post请求")
@PostMapping("postLogin")
public HisResponse postLogin() {
String url = "http://192.168.21.12:8484/api/login?username=admin&pwd=admin";
HisResponse response = httpRestUtil.request(null);
return response;
}
@ApiOperation (value = "调质控添加用户的请求")
@PostMapping("postAddUser")
public HisResponse postAddUser() {
String url = "http://192.168.21.12:8484/api/user/addUser";
//两种传参都行,推荐第一种
JSONObject jsonObject = new JSONObject();
jsonObject.put("username", "dc0825");
jsonObject.put("pwd", "123456");
jsonObject.put("isMaster", 0);
jsonObject.put("organizationId", 0);
jsonObject.put("status", 1);
jsonObject.put("type", 1);
/*String params="{\n" +
" \"isMaster\": 0,\n" +
" \"organizationId\": 0,\n" +
" \"pwd\": \"123456\",\n" +
" \"status\": 0,\n" +
" \"type\": 1,\n" +
" \"userName\": \"dc1111\"\n" +
"}";*/
HisResponse request = httpRestUtil.request (jsonObject.toJSONString ());
return request;
}
}
二、Http请求工具类
/**
* Http请求工具类
*
* @Author: DengChang
* @Date: 2020/8/25 10:09
*/
@Component
public class HttpRestUtil {
private static Logger logger = LoggerFactory.getLogger(HttpRestUtil.class);
/**his请求地址*/
@Value ("${his.url}")
private String URL;
@Autowired
private RestTemplate restTemplate;
/**
* 通用请求方法,可更具情况是否带参数
* @param params,请求数据,格式为json格式的数据 body-raw-json,用作post请求
* @return
*/
public HisResponse request(String params) {
//header参数
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
//TODO 此处做成全局的 his那边登录时如何传头信息再商量
headers.add(BaseConstants.CACHE_REDIS_KEY.UA_SESSION_ID, SpringContextUtil.getBean(SessionUtil.class).getUserSessionId());
HttpEntity<String> request = new HttpEntity<>(params, headers);
//TODO 可以改成his接口返回类
ResponseEntity<String> response = null;
long start = System.currentTimeMillis();
logger.info("request his start----------------------{}millis",start);
try {
response = restTemplate.exchange(URL, HttpMethod.POST, request, String.class);
}
catch (Exception e) {
logger.error("request his failed----------------------{}",e.getMessage(),e);
throw new RuntimeException ("调用失败:"+e);
}
long end = System.currentTimeMillis();
logger.info ("request end----------------------{}millis,process:{}millis", end, end - start);
logger.info("post data----------------------{}", response.getBody());
return JSON.parseObject (response.getBody (), HisResponse.class);
}
}
三、restTemplate 配置类
/**
* restTemplate 配置类
*
* @Author: DengChang
* @Date: 2020/8/25 14:36
*/
@Configuration
public class RestTemplateConfig {
@Value ("${timeout.connect}")
private Integer connect;
@Value("${timeout.read}")
private Integer read;
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
RestTemplate restTemplate = new RestTemplate(factory);
restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
@Override
public void handleError(ClientHttpResponse response) throws IOException {
if (response.getRawStatusCode() != HttpStatus.UNAUTHORIZED.value()) {
super.handleError(response);
}
}
});
StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
restTemplate.setMessageConverters(Collections.singletonList(converter));
return restTemplate;
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(connect);
factory.setReadTimeout(read);
factory.setOutputStreaming(false);
return factory;
}
}
欢迎大神来指点