Java remotely calls the other party's interface
In actual project development, remote interfaces are often needed. How does Java implement the call to remote interfaces? Here we mainly introduce two ways of java calling remote interfaces:
1. Call the remote http interface
Calling third-party http interface through jdk's network class
/** * @Auther kezf * @Date 2020/4/11 * @param urlStr destination address * @param json request parameters * @param charset encoding * @return */ public static String doPost(String urlStr,String json,String charset) { String result = null; ("Request Parameters:"+json); try { //Get the target address URL url = new URL(urlStr); //Create a connection HttpURLConnection connection = (HttpURLConnection) (); //Set the output and input (send data, receive data) to HttpURLConnection. These two parameters must be set when the request is post. (true); (true); //Set request method ("POST"); //Set whether to enable cache. When post request, the cache must be turned off (false); //Set whether the connection automatically handles redirects (setFollowRedirects: the http connection used; setInstanceFollowRedirects: this connection) (true); //Set the submission content type ("Content-Type","application/json"); //Start connection (); //Send a request DataOutputStream out = new DataOutputStream(()); ((charset)); (); (); //Read the response BufferedReader reader = new BufferedReader(new InputStreamReader((), charset)); String lines; StringBuffer sb = new StringBuffer(""); while ((lines = ()) != null) { lines = new String(()); (lines); } result = (); ("Request returns result:"+result); (); // Disconnect (); } catch (MalformedURLException e) { // TODO Auto-generated catch block (); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block (); } catch (IOException e) { // TODO Auto-generated catch block (); } return result; }
2. Call the remote Web Service interface
Call using axis
public String signConfirm(TpgDsfxyxx dsfxyqdxx){ String result=null; try { //Create a service Service service = new Service(); //Create Call object Call call = (Call) (); //Set the address of the service (("dsfxy_qd_url")); //Set the call method name ("SignConfirm"); //Add request parameters ("xyh", XMLType.XSD_STRING, ); ("sqh", XMLType.XSD_STRING, ); ("yzm", XMLType.XSD_STRING, ); ("sfywzl", XMLType.XSD_INTEGER, ); ("jldxhh", XMLType.XSD_STRING, ); ("jldxhm", XMLType.XSD_STRING, ); ("zjlx", XMLType.XSD_STRING, ); ("zjhm", XMLType.XSD_STRING, ); ("dhhm", XMLType.XSD_STRING, ); ("dz", XMLType.XSD_STRING, ); ("fkryhdm", XMLType.XSD_STRING, ); ("fkrkhh", XMLType.XSD_STRING, ); ("fkrzh", XMLType.XSD_STRING, ); ("fkrmc", XMLType.XSD_STRING, ); ("fkrlx", XMLType.XSD_INTEGER, ); (XMLType.XSD_STRING); (()); //Calling the service result = (String) (new Object[]{(()), (), (), (), (), (), (), (), (), (), (), (), (), (), ()}); } catch (Exception e) { throw new RuntimeException(e); } ("signConfirm###:" + result); return result; }
3. The difference between http interface and web service interface
There are two common API interfaces: http interface and webservice interface.
- The http interface adopts the http protocol and distinguishes the call method through paths. The request message is generally in the form of key-value, and the return message is generally a JSON string. The commonly used methods of requesting are used.
- The webservice interface adopts the soap protocol, which transmits through http, request messages and return messages are in XML format.
Encapsulate a Java call remote interface tool class
Java calls remote interface tool class
import ; import ; import ; import ; import ; import ; import ; public class RemoteDemo { //Remote call interface /** * * @param url: remote interface url * @param timeout: Connection timeout * @param object: If the required parameters are json object type, first encapsulate the parameters into JSONObject type * @param method: Send method: post or get * @param contentType: Specify the Content-Type type of HTTP * @return Return is the json string corresponding to the content of the interface */ public static String remoteJsonRequest(String url, int timeout, JSONObject object, String method, String contentType) { URL connect; StringBuffer data = new StringBuffer(); try { connect = new URL(url); HttpURLConnection connection = (HttpURLConnection) (); (method); (true); (timeout); ("Content-Type", contentType); OutputStreamWriter paramout = new OutputStreamWriter((), "UTF-8"); (()); (); InputStream inputStream = (); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8"); BufferedReader reader = new BufferedReader(inputStreamReader); String line; while ((line = ()) != null) { (line); } (); (); } catch (Exception e) { (); } return (); } }
Applicable scenarios
During the development process, we cannot do without accessing certain interfaces directly through the backend to get data, such as interacting or connecting with other platforms.
We will refer to the interface document given by the other party for data access. At this time, we can use this tool class, which is relatively convenient
Brief description of how to use
- Interface parameter transfer method
What is required for the interface isNormal key-value pairs: Pass the parameter directly after the url, pass an empty JSONObject object with the obj parameter. The demo is as follows:
JSONObject obj = new JSONObject(); ("http://localhost:8080/xx/xx?k1=v1&k2=v2", 5000, obj, "POST" ,"application/x-www-form-urlencoded");
What is required for the interface isjson string: The parameters are encapsulated in the JSONObject object, and the demo is as follows:
JSONObject obj = new JSONObject(); ("k1", "v1"); ("k2", "v2"); ("http://localhost:8080/xx/xx", 5000, obj, "POST", "application/json");
In addition, the parameter method and the parameter contentType. Whether the method specifies access requests in post or get mode, it is required to uppercase and pass the string "POST" or "GET"; the contentType parameter is used to specify the Content-Type content corresponding to http. Generally, the corresponding interface document will be given, and we also need to specify it clearly here.
By the way, let’s talk about another parameter JSONObject, which can be used to convert objects and json strings well. From the imported package, we can see that it is using Alibaba; because using Alibaba is more efficient and runs faster; and the low version of JSONObject content has loopholes, so it is necessary to use the highest version as possible.
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.