项目pom文件中加入hutool的依赖,maven更新一下下载工具包
Hutool-http参考文档
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.4.5</version>
</dependency>
然后直接写一个测试类:
package cn.net.sunshine.hisManagement.prescriptionFlow;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import java.util.HashMap;
public class TestMain {
public static void main(String[] args) {
String result = HttpRequest.post("www.baidu.com")//url接口地址
// 1有参 .form("inputData","1")这里是参数(参数名,参数)
.body("")//无参
.execute().body();
System.out.println(result);
}
}
2.还有一种方法:
package com.guomo.app.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.guomo.app.entity.vo.GreentimeVo;
public class test {
public static void main(String[] args) {
//Get接口调用
String url = "http://www.kuaidi100.com/query?type=yuantong&postid=11111111111";
String responseInfo = RestTemplateUtil.get(url, null);
System.out.println(responseInfo);
//Get接口调用请求加上参数,测试用的
String url = "https://***/***/***/***?userid=1&password=1";
String token = "token";
String responseInfo = RestTemplateUtil.get(url, token);
System.out.println(responseInfo);
//Post接口调用
String Url = "http://192.168.3.32:8848/admin/SelectGreenChannel";
ObjectMapper objectMapper = new ObjectMapper();
String data = null;
GreentimeVo userLogin = new GreentimeVo();
try {
data = objectMapper.writeValueAsString(userLogin);
} catch (
JsonProcessingException e) {
e.printStackTrace();
}
String responseInfo2 = RestTemplateUtil.post(Url, data, null);
System.out.println(responseInfo2);
}
}
3.携带token 和参数 调用接口:
String host = "http://localhost:8080";
String path = "/admin/user";//接口地址
String method = "POST";
Map<String, String> headers = new HashMap<String, String>();
headers.put("token", "token码");
Map<String, String> querys = new HashMap<String, String>();
querys.put("参数名", "值");
querys.put("参数名", "值");
Map<String, String> bodys = new HashMap<String, String>();
try {
HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
System.out.println(response.toString());
String toString = EntityUtils.toString(response.getEntity());
System.out.println(toString);
// JSONObject json = JSONObject.fromObject(toString);
//获取response的body
// Object result = json.get("result");
// int i= (int) result;
// System.out.println("返回状态码:"+i);
} catch (Exception e) {
e.printStackTrace();
}
HttpUtils工具类