java一個接口調取另一個接口
工具類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
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 ); /** * 調用對方接口方法 * * @param path * 對方或第三方提供的路徑 * @param data * 向對方或第三方發送的數據,大多數情況下給對方發送JSON數據讓對方解析 * @param requestMethod * 請求方式 * */ 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中使用(接口一)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
@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(); } |
接口二
1
2
3
4
5
6
7
8
9
10
|
@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方法開發類似
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
@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(); } } |
我們調用別人的接口
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
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; } } |
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/qq_33931552/article/details/80907462