1.http接口的格式如下:
图片选择失败,我只能把数据贴出来,如果有不懂的可以问我哈。
http://localhost:8881/department/getDepartmentList接口数据如下:(请求方式是GET)
{
"code":0,
"data":[
{"id":1,"departmentName":"软件研发部","description":"完成对项目的功能,性能,接口,界面等方面的编码工作"},
{"id":2,"departmentName":"软件技术部","description":"编写测试用例,测试软件功能,负责项目的质量审查工作"},
{"id":3,"departmentName":"网络管理部","description":"全面掌握网络运行状况,及时报告网络异常情况及其产生原因并做好记录"},
{"id":4,"departmentName":"市场营销部","description":"配合软件技术部收集整理客户需求工作中有关所有事项"},
{"id":5,"departmentName":"行政部门","description":"主要就是负责行政的工作"},
{"id":6,"departmentName":"财务部门","description":"主要就是管钱,记账"},
{"id":7,"departmentName":"人事部门","description":"负责考情打卡"},
{"id":8,"departmentName":"建库部门","description":"主要负责建库,审核工作"},
{"id":9,"departmentName":"产品部门","description":"负责公司产品推广"}
]
}
http://localhost:8881/department/getDataById?id=3接口数据如下:(请求方式是POST)
{
"code": 0,
"data": {
"id": 3,
"departmentName": "网络管理部",
"description": "全面掌握网络运行状况,及时报告网络异常情况及其产生原因并做好记录"
}
}
2.需要引入的包有:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.42</version>
</dependency>
3.实现方法如下:文章来源:https://www.toymoban.com/news/detail-538845.html
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public static void main(String[] args) {
//处理json字符串
//testJson();
//动态处理json字符串
//commonHttpMethod("http://localhost:8881/department/getDepartmentList", "", "GET");
//commonHttpMethod("http://localhost:8881/department/getDataById", "id=3", "POST");
}
//测试
public static void testJson() {
//1、比如前端接收的是str的json字符串,我们是不能直接获取到名字所对应的值的,所以必须要对这个字符串进行解析。
String str = "{\"code\":\"0\"," +
"\"message\":\"success\"," +
"\"detail\":[\n" +
" {\"userName\":\"userName\",\n" +
" \"password\":123456,\n" +
" \"phoneNum\":\"13877774534\",\n" +
" \"isAdmin\":1,\n" +
" \"alarms\":[24],\n" +
" \"status\":[1,5,7],\n" +
" \"property\":{}\n" +
" }" +
" ]" +
" }";
//2、先转换成JSONObject类型
JSONObject jsonObj = JSON.parseObject(str);
//通过JSONObject中的getString("key")方法,得到对应的值 {"code":"0","message":"success"}这种类型
System.out.println("code:" + jsonObj.getString("code")+" detail:" + jsonObj.getString("detail"));
//3、字符串中含有数组的,比如像detail中的数据
JSONArray jsonInfo = JSONObject.parseArray(jsonObj.getString("detail"));
for (int i = 0; i < jsonInfo.size(); i++) {
JSONObject jsonObject = jsonInfo.getJSONObject(i);
//4、遍历数据,存入数据库【存入数据库直接调用增加的方法即可】
String userName = jsonObject.getString("userName");
String password = jsonObject.getString("password");
String phoneNum = jsonObject.getString("phoneNum");
System.out.println("userName:" + userName + " password:" + password + " phoneNum:" + phoneNum);
}
}
public static void commonHttpMethod(String path, String param, String requestMethod) {
if(requestMethod == "POST") { // POST请求
String postData = interfaceUtil(path, param, requestMethod);
JSONObject jsonObj = JSON.parseObject(postData);
//System.out.println("code:"+ jsonObj.getString("code") + " data:"+jsonObj.getString("data"));
//转成对象 【data为1条数据】
JSONObject result = JSONObject.parseObject(JSONObject.toJSONString(jsonObj.get("data")));
System.out.println("result:" + result);
Integer id = result.getInteger("id");
String departmentName = result.getString("departmentName");
String description = result.getString("description");
System.out.println("id:" + id + " departmentName:" + departmentName + " description:" + description);
}else if(requestMethod == "GET") { // GET请求
String getData = interfaceUtil(path, param, requestMethod);
JSONObject jsonObj = JSON.parseObject(getData);
//System.out.println("code:"+ jsonObj.getString("code") + " data:"+jsonObj.getString("data"));
//转成数组 【data为多条数据】
JSONArray json = JSONObject.parseArray(jsonObj.getString("data"));
System.out.println("json:" + json);
for (int i = 0; i < json.size(); i++) {
JSONObject jsonObject = json.getJSONObject(i);
Integer id = jsonObject.getInteger("id");
String departmentName = jsonObject.getString("departmentName");
String description = jsonObject.getString("description");
System.out.println("size:"+json.size() +" id:" + id + " departmentName:" + departmentName + " description:" + description);
}
}
}
/**
* @调用对方接口方法 向指定 URL发送请求,请求参数为json形式数据
* @param path 对方或第三方提供的路径
* @param param 向对方或第三方发送的数据,大多数情况下给对方发送JSON数据让对方解析
* @param requestMethod 请求方式 GET POST PUT等
* @return
*/
public static String interfaceUtil(String path, String param, String requestMethod) {
String objectData = "";
try {
URL url = new URL(path);
//打开和url之间的连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
PrintWriter out = null;
//设置URLConnection的参数和普通的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
if(requestMethod == "POST") {//发送POST方式的请求,需要获取URLConnection实例对应的输出流来发送请求参数
//设置是否向httpUrlConnection输出,设置是否从httpUrlConnection读入,发送post请求必须设置这两个
//最常用的Http请求无非是get和post,get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet,
//post与get的 不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");//GET和POST必须全大写
out = new PrintWriter(connection.getOutputStream());//获取URLConnection对象对应的输出流
out.print(param);//发送请求参数即数据
out.flush();//缓冲数据
}else if(requestMethod == "GET") {//发送GET方式请求,使用connet方法建立和远程资源之间的实际连接即可
connection.setRequestMethod("GET");//GET和POST必须全大写
connection.connect();
}else {
System.out.println("请重新设置请求方式!");
}
//获取URLConnection对象对应的输入流
InputStream is = connection.getInputStream();
//构造一个字符流缓存
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String str = "";
while ((str = br.readLine()) != null) {
str = new String(str.getBytes(), "UTF-8");//解决中文乱码问题
System.out.println("str:" + str);
objectData = getStringData(str);
}
//关闭流
is.close();
//断开连接,最好写上,disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
//固定多线程的话,如果不disconnect,链接会增多,直到收发不出信息。写上disconnect后正常一些。
connection.disconnect();
System.out.println(requestMethod+"接口调用完毕!");
} catch (Exception e) {
e.printStackTrace();
}
return objectData;
}
public static String getStringData(String value) {
return value;
}
如果文章有用,麻烦点个赞,给个评论,谢谢。文章来源地址https://www.toymoban.com/news/detail-538845.html
到了这里,关于java调用http接口(get请求和post请求)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!