什么是RestTemplate ?
传统情况下在java代码里访问restful服务,一般使用Apache的HttpClient。不过此种方法使用起来太过繁琐。Spring提供了一种简单便捷的模板类来进行操作,这就是RestTemplate。
内置发送get post delete等请求的方法,在SpringBoot中只要导入spring-boot-starter-web的依赖可以直接使用。
为什么说是简单便捷呢?我们来看以下两种实现方式:
/**
* @param url
* @param param
* @param headers
* @param connectTimeout milliseconds
* @param readTimeout milliseconds
* @return
*/
public static String get(String url, String param, Map<String, String> headers, int connectTimeout, int readTimeout) {
BufferedReader in = null;
StringBuilder builder = new StringBuilder();
try {
String urlNameString = url;
if (param != null) {
urlNameString += "?" + param;
}
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", USER_AGENT);
if (connectTimeout > 0) {
conn.setConnectTimeout(connectTimeout);
}
if (readTimeout > 0) {
conn.setReadTimeout(readTimeout);
}
if (headers != null) {
for (Entry<String, String> entry: headers.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
}
conn.connect();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
conn.getInputStream(), DEFAULT_CHARSET));
String line;
while ((line = in.readLine()) != null) {
builder.app