Java accesses other server-side APIs over HTTP.

Source: Internet
Author: User
Tags readline urlencode stringbuffer

To implement such a feature, the user accesses the Python API (algorithm, Java is not good) by clicking the button via Axios to get a result stored in the database and returned to the page.

But Python does not run on Tomcat, so the session is not shared within a domain, and because of security concerns, it is decided to invoke Python's API from Java as a client to get the data.

Start thinking about using Netty, but it doesn't feel necessary to use Java IO and net to do it, and then write a tool class for Java to access any Server API.

The code is as follows, the comments are written and can be used directly.

 PackageCom.sdnuode.nuofe.util;ImportNet.sf.json.JSONArray;ImportNet.sf.json.JSONObject;ImportJava.io.*;Importjava.net.HttpURLConnection;ImportJava.net.URL;ImportJava.net.URLEncoder;ImportJava.util.*; Public classRequestutils {//GET request can only pass one API address parameter     Public StaticArraylistrunrequest (String requesturl) {returnRunrequest (Requesturl, "GET",NewHashmap<>()); }    //Access Server API, three parameters, API address, request method, data/Parameter//Params request pass Map,data request Pass JSON string     Public StaticArraylistrunrequest (String Requesturl, String method, Object info) {StringBuffer buffer=NewStringBuffer ();//used to store return data        Try{URL URL=NewURL (Requesturl);//Create a URL object//handling requests in the form of get and null values            if(method = = "GET") {URL=NewURL (requesturl+ "?") +urlencode (info));//Stitching URL            }            if(Method! = "GET" && Method! = "POST") {                return NewArraylist//only get and post requests are processed and other requests are not processed            }            //Configure connection PropertiesHttpURLConnection httpurlconn = (httpurlconnection) url.openconnection ();//Create a Connection objectHttpurlconn.setdoinput (true);//read in from Httpurlconntion, default TrueHttpurlconn.setdooutput (true);//Post pleading to httpurlconntion read out, default FlaseHttpurlconn.setusecaches (false);//POST request does not use cacheHttpurlconn.setrequestmethod (method);//Request method, default getHttpurlconn.setrequestproperty ("Connection", "keep-alive");//HTTP is recommended for long links, which improves response speedHttpurlconn.setrequestproperty ("Charset", "UTF-8");//character encodingHttpurlconn.setrequestproperty ("Content-type", "Application/json; Charset=utf-8");//Transfer JSON formatHttpurlconn.setrequestproperty ("Accept", "Application/json");//Receive type JSON//Httpurlconn.setrequestproperty ("Accept", "*/*")//violence method Settings Accept all types to prevent 415 from appearing            if(method = = "POST") {                byte[] writebytes = "". GetBytes (); if(Info! =NULL) {writebytes= Info.tostring (). GetBytes ();//byte stream of character flow} httpurlconn.setrequestproperty ("Content-length", String.valueof (Writebytes.length));//Set File lengthOutputStream Outwritestream = Httpurlconn.getoutputstream ();//creating an output stream objectOutwritestream.write (Info.tostring (). GetBytes ());//the contents of the output stream can be passed 3 parameters, from 0 to Len by defaultOutwritestream.flush ();//clear the data (may not finish after reading, buffer has left the possibility)Outwritestream.close ();//turn off the output stream} httpurlconn.connect ();//To start the connection, the configuration information must be set before the connection is completed            intStatusCode = Httpurlconn.getresponsecode ();//Get Status Code            if(StatusCode = = 200) {InputStream InputStream= Httpurlconn.getinputstream ();//Get input stream//stream of byte-flow charactersInputStreamReader InputStreamReader =NewInputStreamReader (InputStream, "Utf-8"); BufferedReader BufferedReader=NewBufferedReader (InputStreamReader);//read stream of charactersString str =NULL; //assigns a stream of characters read to Buffer,readline to read a line, and the current behavior is null, indicating that it has been read                 while(str = bufferedreader.readline ())! =NULL) {buffer.append (str); }                //turn off Bufferreader and input streamsBufferedreader.close ();                Inputstreamreader.close ();                Inputstream.close (); InputStream=NULL;//emptying the input streamHttpurlconn.disconnect ();//Disconnect Connection            }        } Catch(Exception e) {e.printstacktrace (); }        //convert buffer to ArrayList format        if(Buffer.length ()! = 0) {Jsonarray Jsonarray=Jsonarray.fromobject (buffer.tostring ()); ArrayList<HashMap> arrayList =Jsonarrayobjecttoarraylisthashmap (Jsonarray); returnJsonarrayobjecttoarraylisthashmap (Jsonarray); }Else {            return NewArraylist(); }    }    //GET request URL processing     Public StaticString UrlEncode (Object params) {if(Params = =NULL){            return""; } StringBuilder SB=NewStringBuilder (); Map<String,Object> map =(MAP) params;  for(Map.entry i:map.entryset ()) {Try{Sb.append (I.getkey ()). Append ("="). Append (Urlencoder.encode (i.getvalue () + "", "UTF-8"). Append ("&"); } Catch(unsupportedencodingexception e) {e.printstacktrace (); }} String str=sb.tostring (); if(Str.length ()! = 0) {str= Str.substring (0,str.length ()-1); }        returnstr; }    //jsonarray<object> Conversion arraylist     Public StaticArraylistJsonarrayobjecttoarraylisthashmap (Jsonarray jsonarray) {ArrayList<HashMap> arrayList =NewArrayList ();  for(inti = 0;i<jsonarray.size (); i++) {Jsonobject jsonobject=Jsonobject.fromobject (Jsonarray.get (i)); Iterator it=Jsonobject.keys ();  while(It.hasnext ()) {HashMap HashMap=NewHashMap (); String Key=string.valueof (It.next ()); String value=(String) jsonobject.get (key);                Hashmap.put (Key,value);            Arraylist.add (HASHMAP); }        }        returnarrayList; }}

Java accesses other server-side APIs over HTTP.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.