java一个接口调取另一个接口
工具类
package com.utils;
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 org.apache.log4j.Logger;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.userbackend.controller.UserInfoController;
import com.userbackend.model.User;
//调取接口方法
public class ToInterface {
private static final Logger DEBUGGER = Logger.getLogger(UserInfoController.class);
public static StringBuffer interfaceUtil(String path, Object data, String requestMethod) {
StringBuffer sb = new StringBuffer();
DEBUGGER.info("请求数据:" + data);
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 打开和url之间的连接
PrintWriter out = null;
conn.setRequestMethod(requestMethod); // 请求方式
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
//设置传到另一个接口的格式为json
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
// 设置是否向httpUrlConnection输出,设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
// 最常用的Http请求无非是get和post,get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet,
// post与get的 不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
conn.setDoOutput(true);
conn.setDoInput(true);
// allowUserInteraction 如果为 true,则在允许用户交互(例如弹出一个验证对话框)的上下文中对此 URL 进行检查。
conn.setAllowUserInteraction(false);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数即数据
out.print(data);
// 缓冲数据
out.flush();
out.close();
// 获取URLConnection对象对应的输入流
InputStream is = conn.getInputStream();
// 构造一个字符流缓存
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String str = "";
while ((str = br.readLine()) != null) {
sb.append(str);
}
// 关闭流
is.close();
// 断开连接,最好写上,disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
// 固定多线程的话,如果不disconnect,链接会增多,直到收发不出信息。写上disconnect后正常一些。
conn.disconnect();
// System.out.println("完整结束");
DEBUGGER.info("调用app后台接口完整结束");
} catch (Exception e) {
e.printStackTrace();
}
return sb;
}
}
springboot中使用(接口一)
@RequestMapping(value = "/get_all_user", method = RequestMethod.POST)
@ResponseBody
public String get_all_user(HttpServletRequest request, HttpServletResponse response, Model model,
AdminTbl admintabl,User user) {
JSONObject result = new JSONObject();
String[] args = { "admin_id"};
// 判断传来的数据是否为空
JSONObject nullcheck = ParamterNullCheck.getInstance().checkNull(admintabl, args);
JSONObject param = null;
param = (JSONObject) JSON.toJSON(user);
DEBUGGER.info(param.toJSONString());
if (nullcheck == null ) {
// 查询该 用户是否有该权限
admintabl.setUrl("/userInfo/get_all_user");
RolePermissionTbl rpt = permissionService.get_permission(admintabl);
if (rpt != null) {
//调取接口
StringBuffer userlist= ToInterface.interfaceUtil("http://192.168.10.176:20000/user/getUserList",param.toJSONString(),"POST");
result.put("userlist", userlist);
} else {
result.put("msg", Constants.NO_AUTH);
}
}
else {
result = nullcheck;
}
return result.toJSONString();
}
接口二
@RequestMapping(value = "/getUserList", method = RequestMethod.POST)
public ResponseEntity<Response> getUserList(@RequestBody UserPageDto data) {
JSONObject result = new JSONObject();
// 分页语句
Page<Object> page = PageHelper.startPage(data.getPageNo(), 2);
List<User> list = userService.getUserList(data);
result.put("userlist", list); // 总记录数
result.put("pagetotal", page.getTotal());
return success(result);
}
接口的调用与调用别人的接口
此接口调用与被调用,都是在springMVC框架下使用参数以json格式传输。
别人调用我们的接口,与controller方法开发类似
@RequestMapping("/otherUseMe.do")
public void otherUseMe (HttpServletRequest request,HttpServletResponse response) throw IOException{
//基本设置
response.setContent("appliction/json;charset=utf-8");
//用来给对方传递参数
PrintWriter out = response.getWriter();
//系统错误,返回结果
Map<String,Object> exceptionMap = new HashMap<String,Object>();
exceptionMap.put("code","999");
//将错误代码转为json字符串
String exceptionStr = JSONObject.fromObject(excetionMap).toString();
//接收传来的参数
String name = request.getParameter("name");
String gender = request.getParameter("gender");
try{
boolean flag = "业务处理";
if(失败flag){
Map<String,Object> falseMap = new HashMap<String,Object>();
falseMap.put("code","998");
falseMap.put("result","fail");
falseMap.put("description","cry");
String falseStr = JSONObject(falseMap).toString();
out.write(falseStr);
}else{
Map<String,Object> succMap = new HashMap<String,Object>();
falseMap.put("code","997");
falseMap.put("result","succ");
falseMap.put("description","smile");
String succStr = JSONObject(falseMap).toString();
out.write(succStr);
}
}catch(Exception e){
e.printStackTrace();
out.write(exceptionStr);
return;
}finally{
if(out!=null){
out.close();
}
}
我们调用别人的接口
public boolean IUseOthers(String name,String gender){
HttpClient client = new HttpClient();
PostMethod postMethod = new PostMethod("http://111..111.11.11:8080/---");//写网址
postMethod.setRequestHeader("Content-type","application/x-www-form-urlencoded;charset=utf-8");
try{
postMethod.addParameter("name",name);
postMethod.addParameter("gender",gender);
int status = client.executeMethod(postMethod);
//获取返回信息
JSONObject jsonObject = JSONObject.fromObject(postMethod.getResponBodyAsString().toString);
String code = jsonObject.getString("code");
boolean flag = false;
if("999".equals(code)){
flag =true;
}
}catch(HttpException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
if(postMehod!=null){
postMehod.releaseConnection();
}
}
return flag;
}
}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。