关于在Java中调用REST接口,首先来讲一下JAX-RS。html
JAX-RS是JAVA EE6 引入的一个新技术。JAX-RS即Java API for RESTful Web Services,是一个Java 编程语言的应用程序接口,支持按照表述性状态转移(REST)架构风格建立Web服务。JAX-RS使用了Java SE5引入的Java注解来简化Web服务的客户端和服务端的开发和部署。java
Java提供的JAX-RS自己就能够实现调接口的功能,使用比较简单,可是我目前还没发现怎么设置超时时间,使用的代码以下:web
package com.util; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; public class TestC { /** * * @param url 请求地址 * @param postParam 参数 * @param mediaType 媒体类型 * @return */ public static String post(String url, String postParam, MediaType mediaType) { Client client = ClientBuilder.newClient(); String result = null; WebTarget target = client.target(url); Response response = target.request().post(Entity.entity(postParam, mediaType)); try { if (response.getStatus() != 200) { throw new RuntimeException("Failed with HTTP error code : " + response.getStatus()); } result = response.readEntity(String.class); } catch (Exception e) { e.printStackTrace(); } finally { response.close(); client.close(); } return result; } }
除了Java自己的JAX-RS以外,还有不少别的框架,有的扩展了Java的JAX-RS,有的使用http链接的方式,都能实现调接口的目的,并且功能更增强大,下面举例两种,分别是Apache的HttpClient和Spring的RestTemplate,都是能够设置超时时间的。spring
使用代码以下:apache
package com.util; import org.apache.http.HttpEntity; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.util.EntityUtils; public class TestA { /** * * @param url 请求地址 * @param param 参数 * @param mediaType 媒体类型值 * @param connectTimeout 链接超时时间,单位是毫秒,设置为0表示不限长 * @param readTiemout 调用超时时间,单位是毫秒,设置为0表示不限长 * @return */ public String postWithTimeout(String url, String param,String mediaType, int connectTimeout, int readTiemout) { String result = null; HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); try { httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeout);// 设置创建链接超时时间 httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, readTiemout);// 设置等待返回超时时间 StringEntity entity = new StringEntity(param); entity.setContentEncoding("UTF-8"); entity.setContentType(mediaType); httpPost.setEntity(entity); HttpEntity resEntity = httpClient.execute(httpPost).getEntity(); result = EntityUtils.toString(resEntity, "UTF-8"); } catch (Exception e) { e.printStackTrace(); } finally { httpClient.getConnectionManager().shutdown(); } return result; } }
使用代码以下:编程
package com.util; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; public class TestB { /** * * @param url 请求地址 * @param param 参数 * @param mediaType 媒体类型值 * @param connectTimeout 链接超时时间,单位是毫秒,设置为0表示不限长 * @param readTiemout 调用超时时间,单位是毫秒,设置为0表示不限长 * @return */ public static String postWithTimeout(String url, String body, String mediaType, int connectTimeout, int readTiemout) { SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); requestFactory.setConnectTimeout(connectTimeout);// 设置创建链接超时时间 requestFactory.setReadTimeout(readTiemout);// 设置等待返回超时时间 RestTemplate restTemplate = new RestTemplate(requestFactory); HttpHeaders headers = new HttpHeaders(); MediaType type = MediaType.parseMediaType(mediaType); headers.setContentType(type); headers.add("Accept", "text/html,application/xhtml+xml,application/json;q=0.9,*/*;q=0.8"); headers.add("Content-Length", "0"); HttpEntity<String> formEntity = new HttpEntity<String>(body, headers); String temp = restTemplate.postForObject(url, formEntity, String.class); return temp; } }
Spring的RestTemplate和Apache的HttpClient同样,能够设置创建链接的超时时间,和等待服务器返回的超时时间,这两个超时时间的单位都是毫秒,若是设置为0,表示没有超时时间。json
他们也都支持get,post等请求方式,比Java源生的JAX-RS功能要丰富一些服务器
实际上RestTemplate也是使用了HttpClient的原理,而HttpClient就是扩展自Java的JAX-RS。架构
其余的框架如Jersey等,也能够实现以上相似的功能,这种框架有不少,能够慢慢学习。app