引入pom依赖
<!-- RestTemplate -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.10</version>
</dependency><!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.60</version>
</dependency>
<!--import org.springframework.http.*-->
<properties> <org.springframework.version>4.3.19.RELEASE</org.springframework.version> </properties> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${org.springframework.version}</version> </dependency>
解决org.springframework.web.client.RestTemplate‘ that could not be found.
// 添加一个配置类注入到springboot里
@Configuration public class HttpConfig { @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { builder.setConnectTimeout(Duration.ofSeconds(15L)) .setReadTimeout(Duration.ofMinutes(300L)); return builder.build(); }/** * https * https是不能直接使用ip地址调用接口的 * @return RestTemplate * @throws KeyStoreException KeyStoreException * @throws NoSuchAlgorithmException NoSuchAlgorithmException * @throws KeyManagementException KeyManagementException * @Resource(name = "restTemplate2") * private RestTemplate restTemplate; */ @Bean(name = "restTemplate2") public RestTemplate restTemplate2() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException { HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); factory.setConnectionRequestTimeout(60000); factory.setConnectTimeout(10000); factory.setReadTimeout(60000); // https SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, (X509Certificate[] x509Certificates, String s) -> true); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(builder.build(), new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", new PlainConnectionSocketFactory()) .register("https", socketFactory).build(); PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(registry); poolingHttpClientConnectionManager.setMaxTotal(200); CloseableHttpClient httpClient = HttpClients.custom() .setSSLSocketFactory(socketFactory) .setConnectionManager(poolingHttpClientConnectionManager) .setConnectionManagerShared(true) .build(); factory.setHttpClient(httpClient); return new RestTemplate(factory); }}
调用https接口报错也可参考:
No subject alternative names present
使用RestTemplate调用外部https接口_resttemplate调用https_新时代打工崽的博客-CSDN博客
postForObject方法
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.longfor.budget.api.config.LtUrlProperties;
import com.longfor.budget.api.dao.entity.TLtPushBackApi;
import com.longfor.budget.api.dao.mapper.TLtPushBackApiMapper;
import com.longfor.budget.api.repo.Result;
import com.longfor.budget.api.service.TLtPushBackApiService;
import com.longfor.budget.api.service.ToLtResultDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
@Resource
private RestTemplate restTemplate;
//方法中代码
String url = ltUrlProperties.getCalculateUrl();
log.info("返回测算信息url======={}",url);
Map<String, Object> errReturn = new HashMap<>();
errReturn.put("code","500");
errReturn.put("message","测算失败");
errReturn.put("versionNo",versionCodeAndUcode.getVersionCode());
errReturn.put("uniqueId",versionCodeAndUcode.getUniqueId());
JSONObject jsonObject = JSONUtil.parseObj(errReturn);
String jsonStringErr = JSONUtil.toJsonStr(jsonObject);
// String jsonStringErr = JSON.toJSONString(ImmutableMap.of("userId", userId), SerializerFeature.WriteMapNullValue);
log.info("发送给龙头的测算返回信息=========={}",jsonStringErr);
HttpHeaders headersErr = new HttpHeaders();
headersErr.setContentType(MediaType.APPLICATION_JSON_UTF8);
headersErr.add("token", "我是token");
HttpEntity<String> httpEntityErr = new HttpEntity<>(jsonStringErr, headersErr);
String responseErr = this.restTemplate.postForObject(url, httpEntityErr, String.class);
log.info("龙头接收返回信息=========={}",responseErr);
getForObject方法
@Resource
private RestTemplate restTemplate;
String url = appConfig.getC1tm().getPushToC2()+"f_code="+c1InterfaceApi.getProjectCode()+"&version="+c1InterfaceApi.getVersion();
JSONObject result = this.restTemplate.getForObject(url,JSONObject.class);
log.info("返回数据:{}",result.toString());
exchange方法之post
Map<String, Object> requestMap = ImmutableMap.of("Parameters", parameters);
String jsonString = JSONObject.toJSONString(requestMap);
String requestURL = url;
log.info("=======调用接口: {}", requestURL);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Authorization", "Basic " + encodeBase64String(username, password));
HttpEntity<String> httpEntity = new HttpEntity<>(jsonString, headers);
ResponseEntity<String> responseEntity = this.restTemplate.exchange(requestURL, HttpMethod.POST, httpEntity, String.class);
log.info("=======调用接口response: {}", responseEntity);
exchange方法之get
StringBuilder strBu = new StringBuilder();
strBu.append("?versionCode=").append(versionCode);
strBu.append("&projectCode=").append(projectCode);
String parseC3ExcelUrl = url;
parseC3ExcelUrl = parseC3ExcelUrl + strBu.toString();
String apiKey = this.config.getZncsConfig().getGaiaApiKey();
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("X-Gaia-Api-Key",apiKey);
HttpEntity<String> entity = new HttpEntity<>("parameters",httpHeaders);
log.info("接口调用:"+parseC3ExcelUrl+"===="+apiKey);
ResponseEntity<String> responseEntity = restTemplate.exchange(parseC3ExcelUrl, HttpMethod.GET,entity,String.class);
log.info("接口响应:"+responseEntity.getStatusCode() + responseEntity.getBody());
x-www-form-urlencoded格式请求
String url = this.appConfig.getNcConfig().getTokenUrl();
String clientId = this.appConfig.getNcConfig().getClientId();
String clientSecret = this.appConfig.getNcConfig().getClientSecret();
String token = null;
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> param = new LinkedMultiValueMap<>(3);
param.add("client_id", clientId);
param.add("client_secret", clientSecret);
param.add("grant_type", "client_credentials");
HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(param, headers);
String result = restTemplate.postForObject(url, httpEntity, String.class);
if (StringUtils.isNotBlank(result)) {
JSONObject jsonResult = JSONObject.parseObject(result);