java使用HttpURLConnection实现后端调用其他服务接口汇总Rest服务
一、java原生的 HttpURLConnection
1、代码实现:
/**
* description: 使用 HttpURLConnection 实现调用其他服务接口
* @param location 请求地址
* @param requestMethod 请求方式
* @param params 需求提交到服务端的参数,格式: name=xiaoming&age=18
* @param encoding 编码格式
* @return void
* @version v1.0
* @author w
* @date 2019年2月24日 下午2:13:23
*/
public static String doRequest(String location , String requestMethod , String params ,String encoding) throws Exception{
URL url = new URL(location);
HttpURLConnection connection =(HttpURLConnection) url.openConnection();
connection.setRequestMethod(requestMethod); // 设置请求方式 GET、POST 等
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setConnectTimeout(2000); // 设置连接超时时间,单位:ms 。
connection.setReadTimeout(2000); // 设置读取超时时间,单位:ms 。
connection.setDoInput(true); // 设置打开输入流 : default = true
connection.setDoOutput(true); // 设置打开输出流:default = false
connection.setUseCaches(false); // 设置是否启用用户缓存: default = false
OutputStream outputStream = connection.getOutputStream(); // 获取输出流对象,准备往服务器写数据
outputStream.write(params.getBytes());
outputStream.flush();
outputStream.close();
// 获取服务器返回的响应状态
if(connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
System.out.println(" request fail ...");
return connection.getResponseMessage();
}
// 读取服务器返回的数据
BufferedReader reader = new BufferedReader(new
InputStreamReader(connection.getInputStream(), encoding));
String line ;
StringBuffer sb = new StringBuffer();
while((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
String result = sb.toString();
System.out.println(result);
return result ;
}
2、代码测试:
public static void main(String[] args) {
String params = "";
String location = "http://ip.taobao.com/service/getIpInfo.php"; params = "ip=1.98.132.223" ;
//String location = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
String requestMethod = "POST" ;
try {
doRequest(location, requestMethod, params, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
}
二、HttpClient.jar 实现
1、请移步链接: java中使用HttpClient实现服务端跨域
三、Spring RestTemplate 实现
1、依赖jar包: spring-web-4.x.jar
2、简单代码实现:
/**
* description: Spring RestTemplate test
* @version v1.0
* @author w
* @date 2019年2月24日下午3:45:37
**/
public class RestTemplateTest {
public static void main(String[] args) {
RestTemplate rest = new RestTemplate();
String location = "http://ip.taobao.com/service/getIpInfo.php?ip=ip=1.98.132.223";
ResponseEntity<String> entity = rest.getForEntity(location, String.class );
String body = entity.getBody();
System.out.println(body);
}
}
3、关于Spring RestTemplate请参考: 详解 RestTemplate 操作