系统间的交互,除了webservice,最简单应该就是http方式。
比如微信平台、支付宝、微博、QQ的api调用。
常用的方式及example:
- JDK 提供的机制
/**
* 最简单的使用,参考:https://developer.android.com/reference/java/net/HttpURLConnection.html
*/
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
} finally {
urlConnection.disconnect();
}
/**
* 带cookie 的post请求
* cookie设置是系统级别的,jvm通用
**/
public static void main(String[] args) throws IOException, URISyntaxException {
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
HttpCookie cookie = new HttpCookie("sso.dd.com", "b1846e53e99c7");
cookie.setDomain(".dd.com");
cookie.setPath("/");
cookieManager.getCookieStore().add(new URI("http://erp.dd.com/"), cookie);
URL url = new URL("http://erp.dd.com/portal/clock/clockInfo");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(1000);
connection.setConnectTimeout(1000);
connection.setRequestMethod("POST");
try {
InputStream in = new BufferedInputStream(connection.getInputStream());
readStream(in);
} finally {
connection.disconnect();
}
}
/**
* spring-web的封装
* 参考:org.springframework.http.client.SimpleClientHttpRequestFactory
* 参考:org.springframework.web.client.RestTemplate
*/
- httpcomponents-client
/**
* 重试机制,比如重试次数、根据Exception类型、或者动态调整重试请求
**/
public static HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() {
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
System.out.println(exception.getMessage());
if (executionCount <= 5) {
// Do not retry if over max retry count
return true;
}
return false;
}
};
/**
* 使用httpcomponents-client 发送get请求
**/
public static void main(String[] args) throws IOException {
// CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpClient httpClient = HttpClients.custom().setRetryHandler(myRetryHandler).build();
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000).setConnectTimeout(1000).build();
HttpGet httpget = new HttpGet("http://api.github.com/users/PivotalSoftware");
httpget.setConfig(requestConfig);
CloseableHttpResponse response = httpClient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
try {
readStream(instream);
} finally {
instream.close();
}
}
} finally {
response.close();
}
}
参考: 基础使用方式
okhttp
// TODO