In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article is about how java implements one interface to call another. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
Java calls one interface to another interface tool class 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 / / call the interface method public class ToInterface {/ * to test the logger. * / private static final Logger DEBUGGER = Logger.getLogger (UserInfoController.class) / * call the other party's interface method * * @ param path* the path provided by the other party or the third party * @ param data* to send data to the other party or the third party. In most cases, send JSON data to the other party to parse * @ param requestMethod* request method * * / public static StringBuffer interfaceUtil (String path, Object data, String requestMethod) {StringBuffer sb = new StringBuffer () DEBUGGER.info ("request data:" + data); try {URL url = new URL (path); HttpURLConnection conn = (HttpURLConnection) url.openConnection (); / / Open connection to url PrintWriter out = null;conn.setRequestMethod (requestMethod); / / request method / / set common request properties conn.setRequestProperty ("accept", "* / *"); conn.setRequestProperty ("connection", "Keep-Alive") / / set the format to be transferred to another interface as jsonconn.setRequestProperty ("Content-Type", "application/json;charset=UTF-8"); conn.setRequestProperty ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)") / / set whether to output to httpUrlConnection and whether to read from httpUrlConnection. In addition, to send post requests, you must set these two / / most commonly used Http requests: get and post,get requests can get static pages, or you can put parameters after the URL string. The difference passed to servlet,// post and get is that the parameters of post are not placed in the URL string, but in the body of the http request. Conn.setDoOutput (true); conn.setDoInput (true); / / allowUserInteraction if true, the URL is checked in a context that allows user interaction (such as a pop-up authentication dialog box). Conn.setAllowUserInteraction (false); / / get the output stream corresponding to the URLConnection object out = new PrintWriter (conn.getOutputStream ()); / / send request parameters namely data out.print (data); / / buffer data out.flush (); out.close (); / / get the input stream corresponding to the URLConnection object InputStream is = conn.getInputStream (); / / construct a character stream cache BufferedReader br = new BufferedReader (new InputStreamReader (is)); String str = "" While ((str = br.readLine ())! = null) {sb.append (str);} / closes the stream is.close (); / / disconnects, preferably writing that disconnect is only cut when the underlying tcp socket link is idle. It is not cut off if it is being used by another thread. / / fixed multithreading, if not disconnect, the number of links will increase until messages cannot be sent or sent. It is more normal after writing disconnect. Conn.disconnect (); / / System.out.println ("complete termination"); DEBUGGER.info ("complete termination of calling app backend API");} catch (Exception e) {e.printStackTrace ();} return sb;}} springboot (API 1) @ 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"}; / / determine whether the incoming data is empty JSONObject nullcheck = ParamterNullCheck.getInstance (). CheckNull (admintabl, args); JSONObject param = null;param = (JSONObject) JSON.toJSON (user); DEBUGGER.info (param.toJSONString ()); if (nullcheck = = null) {/ / query whether the user has the permission admintabl.setUrl ("/ userInfo/get_all_user"); RolePermissionTbl rpt = permissionService.get_permission (admintabl) If (rpt! = null) {/ / call interface 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 () } Interface 2 @ RequestMapping (value = "/ getUserList", method = RequestMethod.POST) public ResponseEntity getUserList (@ RequestBody UserPageDto data) {JSONObject result = new JSONObject (); / / paging statement Page page = PageHelper.startPage (data.getPageNo (), 2); List list = userService.getUserList (data); result.put ("userlist", list); / / Total number of records result.put ("pagetotal", page.getTotal ()); return success (result);} call of interface and calling other people's interface
Both this API and the called API are transmitted in json format using parameters under the springMVC framework.
When someone calls our interface, it is similar to the development of controller method @ RequestMapping ("/ otherUseMe.do") public void otherUseMe (HttpServletRequest request,HttpServletResponse response) throw IOException {/ / basic setting response.setContent ("appliction/json;charset=utf-8"); / / is used to pass the parameter PrintWriter out = response.getWriter () to the other party; / / system error returns the result Map exceptionMap = new HashMap (); exceptionMap.put ("code", "999") / / convert the error code to the json string String exceptionStr = JSONObject.fromObject (excetionMap). ToString (); / / receive the incoming parameters String name = request.getParameter ("name"); String gender = request.getParameter ("gender"); try {boolean flag = "business processing"; if (failed flag) {Map falseMap = new HashMap (); falseMap.put ("code", "998"); falseMap.put ("result", "fail") FalseMap.put ("description", "cry"); String falseStr = JSONObject (falseMap). ToString (); out.write (falseStr);} else {Map succMap = new HashMap (); 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 (outdated null) {out.close ();}} We call someone else's interface public boolean IUseOthers (String name,String gender) {HttpClient client = new HttpClient (); PostMethod postMethod = new PostMethod ("http://111..111.11.11:8080/---"); / / write the URL 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); / / get the return information 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.releaseConnection ();}} return flag;}} Thank you for reading! This is the end of this article on "how to implement one interface and call another interface in java". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.