欢迎转载:攻城狮不是猫
{"Author": "tomcat and jerry","url":"/tomcatandjerry/p/5899722.html" }
Spring RestTemplate, 使用java访问URL更加优雅,更加方便。
核心代码:
String url = "http://localhost:8080/json";JSONObject json = restTemplate.getForEntity(url, JSONObject.class).getBody();
就这么简单,API访问完成了!
附上SpringBoot相关的完整代码:
RestTemplateConfig.java@Configurationpublic class RestTemplateConfig{@Beanpublic RestTemplate restTemplate(ClientHttpRequestFactory factory){return new RestTemplate(factory);}@Beanpublic ClientHttpRequestFactory simpleClientHttpRequestFactory(){SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();factory.setReadTimeout(5000);//msfactory.setConnectTimeout(15000);//msreturn factory;}}
SpringRestTemplateApp.java@RestController@EnableAutoConfiguration@Import(value = {Conf.class})public class SpringRestTemplateApp {@AutowiredRestTemplate restTemplate;/***********HTTP GET method*************/@RequestMapping("")public String hello(){String url = "http://localhost:8080/json";JSONObject json = restTemplate.getForEntity(url, JSONObject.class).getBody();return json.toJSONString();}@RequestMapping("/json")public Object genJson(){JSONObject json = new JSONObject();json.put("descp", "this is spring rest template sample");return json;}/**********HTTP POST method**************/@RequestMapping("/postApi")public Object iAmPostApi(@RequestBody JSONObject parm){System.out.println(parm.toJSONString());parm.put("result", "hello post");return parm;}@RequestMapping("/post")public Object testPost(){String url = "http://localhost:8080/postApi";JSONObject postData = new JSONObject();postData.put("descp", "request for post");JSONObject json = restTemplate.postForEntity(url, postData, JSONObject.class).getBody();return json.toJSONString();}public static void main(String[] args) throws Exception {SpringApplication.run(SpringRestTemplateApp.class, args);}}
===============================
另外还支持异步调用AsyncRestTemplate
@RequestMapping("/async")public String asyncReq(){String url = "http://localhost:8080/jsonAsync";ListenableFuture<ResponseEntity<JSONObject>> future = asyncRestTemplate.getForEntity(url, JSONObject.class);future.addCallback(new SuccessCallback<ResponseEntity<JSONObject>>() {public void onSuccess(ResponseEntity<JSONObject> result) {System.out.println(result.getBody().toJSONString());}}, new FailureCallback() {public void onFailure(Throwable ex) {System.out.println("onFailure:"+ex);}});return "this is async sample";}
================================
贴一段post请求如何自定义header
@RequestMapping("/headerApi")//模拟远程的restful APIpublic JSONObject withHeader(@RequestBody JSONObject parm, HttpServletRequest req){System.out.println("headerApi====="+parm.toJSONString());Enumeration<String> headers = req.getHeaderNames();JSONObject result = new JSONObject();while(headers.hasMoreElements()){String name = headers.nextElement();System.out.println("["+name+"]="+req.getHeader(name));result.put(name, req.getHeader(name));}result.put("descp", "this is from header");return result;}@RequestMapping("/header")public Object postWithHeader(){//该方法通过restTemplate请求远程restfulAPIHttpHeaders headers = new HttpHeaders();headers.set("auth_token", "asdfgh");headers.set("Other-Header", "othervalue");headers.setContentType(MediaType.APPLICATION_JSON);JSONObject parm = new JSONObject();parm.put("parm", "1234");HttpEntity<JSONObject> entity = new HttpEntity<JSONObject>(parm, headers);HttpEntity<String> response = restTemplate.exchange("http://localhost:8080/headerApi", HttpMethod.POST, entity, String.class);//这里放JSONObject, String 都可以。因为JSONObject返回的时候其实也就是stringreturn response.getBody();}
访问https
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;import org.apache.http.conn.ssl.TrustStrategy;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.springframework.http.ResponseEntity;import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;import org.springframework.web.client.RestTemplate;import .ssl.SSLContext;import java.security.KeyManagementException;import java.security.KeyStoreException;import java.security.NoSuchAlgorithmException;import java.security.cert.X509Certificate;public class WeixinTest {public static void main(String[] args) throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {String appid = "";String secret = "";String grant_type = "";String js_code = "";String url = "https://api./sns/jscode2session?appid="+appid+"&secret="+secret+"&js_code="+js_code+"&grant_type="+grant_type;/* SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();factory.setReadTimeout(5000);//msfactory.setConnectTimeout(15000);//msRestTemplate restTemplate = new RestTemplate(factory);*/ResponseEntity<String> responseEntity = restTemplate().getForEntity(url, String.class);System.out.println(responseEntity.getBody());}public static RestTemplate restTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();HttpComponentsClientHttpRequestFactory requestFactory =new HttpComponentsClientHttpRequestFactory();requestFactory.setHttpClient(httpClient);RestTemplate restTemplate = new RestTemplate(requestFactory);return restTemplate;}
maven
<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.3</version></dependency>
这里使用httpclient的factory
配置
@Beanpublic RestTemplate restTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();HttpComponentsClientHttpRequestFactory requestFactory =new HttpComponentsClientHttpRequestFactory();requestFactory.setHttpClient(httpClient);RestTemplate restTemplate = new RestTemplate(requestFactory);return restTemplate;}
验证
@Testpublic void testHttps(){String url = "https://free-/v5/forecast?city=CN101080101&key=5c043b56de9f4371b0c7f8bee8f5b75e";String resp = restTemplate.getForObject(url, String.class);System.out.println(resp);}