本篇将主要介绍如何使用HttpURLConnection对象调用本地普通、restful接口的实例.(实现代码中有大量注释供理解所用)
先准备好一个Springboot项目,方便自己编写接口与后台直接main方法调用.
Springboot工程结构展示:
第一步,我们先简单的在Controller层中编写两个不同类型的GET方法接口.
一个是普通的GET方法接口,简易代码如下:
@ResponseBody
@RequestMapping(value = "/user/msg",method = {RequestMethod.GET})
public String getUserMsg(@RequestParam("id")int id){
System.out.println("GET请求需要获取Id为"+id+"的用户...");
return "GET请求需要获取Id为"+id+"的用户...";
}
另一个是restful的GET方法接口,简易代码如下:
@ResponseBody
@RequestMapping(value = "/user/{id}",method = {RequestMethod.GET})
public String getUserMsgRestful(@PathVariable("id")int id){
System.out.println("GET请求需要获取Id为"+id+"的用户...");
return "GET请求需要获取Id为"+id+"的用户...";
}
接口创建好后,启动Springboot项目,在浏览器上测试下接口
测试结果如下:
接口验证可用后,第二步便是编写HttpURLConnection工具类,然后直接main方法调用两种接口即可.
public static String doGet(String httpUrl,Map<String,Object> params){
String result = null;
//try..catch语句外声明资源,方便finally统一进行关闭
HttpURLConnection httpURLConnection = null;
InputStream is = null;
BufferedReader br = null;
try{
//判断get请求是否需要携带参数
if(!params.isEmpty()){
Set<String> keySet = params.keySet();
Iterator iterator = keySet.iterator();
StringBuffer stringBuffer = new StringBuffer();
while (iterator.hasNext()){
String key = (String)iterator.next();
Object value = (Object)params.get(key);
// 1.普通get接口拼接参数方式: url?param1=value1¶m2=value2...
if(stringBuffer.toString().equals("")){
stringBuffer.append("?");
} else {
stringBuffer.append("&");
}
stringBuffer.append(key);
stringBuffer.append("=");
stringBuffer.append(value);
// 2.restful接口拼接参数方式:url/{param1}/{param2}
/*stringBuffer.append("/");
stringBuffer.append(value);*/
}
httpUrl += stringBuffer.toString();
System.out.println("GET请求接口地址"+httpUrl);
}
URL url = new URL(httpUrl);
//通过指定url开启一个连接
httpURLConnection = (HttpURLConnection)url.openConnection();
//声明发送GET请求类型
httpURLConnection.setRequestMethod("GET");
httpURLConnection.connect();
//HTTP:200状态码表示请求已成功
if(httpURLConnection.getResponseCode()==200){
is = httpURLConnection.getInputStream();
//缓冲输入流包装字符输入流,放入内存中,字符读取效率更快.
br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
StringBuffer stringBuffer = new StringBuffer();
String line = null;
while((line = br.readLine())!=null){
//将每次读取的行进行保存
stringBuffer.append(line);
stringBuffer.append("\r\n");
}
result = stringBuffer.toString();
}
}catch(Exception e){
e.printStackTrace();
}finally {
try{
//依次关闭开启的资源
if(br!=null){
br.close();
}
if(is!=null){
is.close();
}
httpURLConnection.disconnect();
} catch(Exception e){
e.printStackTrace();
}
}
return result;
}
注意此处!由于访问普通接口和访问restful接口携带参数的方式不同,所以需要编写两种URL拼接方式.
while (iterator.hasNext()){
String key = (String)iterator.next();
Object value = (Object)params.get(key);
// 1.普通get接口拼接参数方式: url?param1=value1¶m2=value2...
if(stringBuffer.toString().equals("")){
stringBuffer.append("?");
} else {
stringBuffer.append("&");
}
stringBuffer.append(key);
stringBuffer.append("=");
stringBuffer.append(value);
// 2.restful接口拼接参数方式:url/{param1}/{param2}
/*stringBuffer.append("/");
stringBuffer.append(value);*/
}
第三步,便可以在HttpURLConnection工具类main方法中调用doGet方法.访问两种接口.
1. 调用普通接口
public static void main(String[] args) {
Map<String,Object> params = new HashMap<>();
params.put("id",1);
System.out.println(doGet("http://127.0.0.1:8080/user/msg",params));
}
调用结果如下图:
main程序输出返回值如下:
Springboot接口输出结果如下:
2.调用restful接口
调用结果如下图:
main程序输出返回值如下:
Springboot接口输出结果如下:
以上便完成了使用HttpURLConnection对象向普通和restful接口发送GET请求的任务