本篇将主要介绍如何使用HttpURLConnection对象调用POST接口的实例.(实现代码中有大量注释供理解所用)
先准备好一个Springboot项目,方便自己编写接口与后台直接main方法调用.
Springboot工程结构展示:
准备好后,第一步先简单的在Controller层中编写基于POST方法的接口.
1.POST请求一般用于提交数据,所以先创建一个User实体类用于自动接收参数.(记得重写toString()方法,方便查看属性值)
public class User {
private int id;
private String username;
private String password;
public User(){
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
2.在Controller层,编写POST请求的接口
@ResponseBody
@RequestMapping(value = "/user/save",method = {RequestMethod.POST})
public String saveUserMsg(User user){
//因重写了User的toString()方法,会直接输出属性值
System.out.println(user);
return "保存用户已执行...";
}
由于此接口是基于POST方法的,所以无法在浏览器中测试.可以使用SoapUI或Postman等接口测试工具测试.
第二步,编写HttpURLConnection工具类,然后直接main方法调用POST接口即可.
public static String doPost(String httpUrl,Map<String,Object> params){
String result = null;
//try..catch外声明资源,方便finally统一关闭资源
HttpURLConnection httpURLConnection = null;
OutputStream os = null;
DataOutputStream out = null;
InputStream is = null;
BufferedReader br = null;
try{
URL url = new URL(httpUrl);
//通过指定url开启一个连接
httpURLConnection = (HttpURLConnection)url.openConnection();
//声明发送POST请求类型
httpURLConnection.setRequestMethod("POST");
//注意:当向服务器传送数据时,setDoOutput方法要设置成true.默认为false
httpURLConnection.setDoOutput(true);
//设置请求报头信息
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//开启连接
//httpURLConnection.connect();
//获取连接对象的字符输出流对象
// 【注意此处,getOutputStream方法会自动的进行connect连接.
// 所以不需要手动编写httpURLConnection.connect();】
out = new DataOutputStream(httpURLConnection.getOutputStream());
StringBuffer stringBuffer = new StringBuffer();
//判断是否携带参数
if(!params.isEmpty()){
Set<String> keySet = params.keySet();
Iterator iterator = keySet.iterator();
while (iterator.hasNext()){
String key = (String)iterator.next();
Object value = (Object)params.get(key);
if(!stringBuffer.toString().equals("")){
stringBuffer.append("&");
}
stringBuffer.append(key);
stringBuffer.append("=");
stringBuffer.append(URLEncoder.encode(value.toString(),"UTF-8"));
}
}
//将参数写入httpURLConnection对象的输出流
out.writeBytes(stringBuffer.toString());
//HTTP:200状态码表示请求已成功
if(httpURLConnection.getResponseCode()==200){
//请求成功后,响应值可从httpURLConnection对象的输入流中读取
is = httpURLConnection.getInputStream();
//缓冲流包装字符输入流,放入内存中,读取效率更快
br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
StringBuffer stringBuffer1 = new StringBuffer();
String line = null;
while((line = br.readLine())!=null){
//将每次读取的行进行保存
stringBuffer1.append(line);
stringBuffer1.append("\r\n");
}
result = stringBuffer1.toString();
}
} catch(Exception e){
e.printStackTrace();
}finally {
try{
//依次关闭资源
if(br!=null){
br.close();
}
if(is!=null){
is.close();
}
if(out!=null){
out.close();
}
if(os!=null){
os.close();
}
httpURLConnection.disconnect();
} catch(Exception e){
e.printStackTrace();
}
}
return result;
}
第三步,便可以在HttpURLConnection工具类main方法中调用doPost方法.访问POST接口.
public static void main(String[] args) {
Map<String,Object> params = new HashMap<>();
params.put("id",1);
params.put("username","shanghai");
params.put("password","000000");
System.out.println(doPost("http://127.0.0.1:8080/user/save",params));
}
调用结果如下图:
main程序输出返回值如下:
Springboot接口输出结果如下:
以上便完成了使用HttpURLConnection对象向接口发送POST请求的任务