SpringBoot跨域-http
<h6>SpringBoot解决跨域</h6>
<pre><code>package com.example.two.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CoreConfig {
/**
* 超时时间2分钟
*/
private int outtime = 2 * 60 * 1000;
/**
* http 调用
*
* @return
*/
@Bean
public RestTemplate restTemplate() {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setConnectTimeout(outtime);
requestFactory.setReadTimeout(outtime);
return new RestTemplate(requestFactory);
}
/**
* 跨域处理
*
* @return
*/
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("*");
config.setAllowCredentials(true);
config.addAllowedMethod("*");
config.addAllowedHeader("*");
UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
configSource.registerCorsConfiguration("/**", config);
return new CorsFilter(configSource);
}
}
</code></pre>
<h5>封装Http-post</h5>
<pre><code>package com.example.two.config;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class HttpService {
private Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
private RestTemplate restTemplate;
/**
* post请求
*
* @param jsonObject 请求参数
* @param url 接口地址
* @return json
*/
public JSONObject post(String url,JSONObject jsonObject) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
ResponseEntity<JSONObject> resp = restTemplate.postForEntity(url, jsonObject, JSONObject.class);
JSONObject rtnJson = resp.getBody();
log.info(rtnJson.toJSONString());
return rtnJson;
}
}
</code></pre>