Generally in the *.html,*.jsp page we use AJAX to call the interface, this is what we usually use. For these interfaces, most of the company is written by the interface for their own calls, so directly with Ajax can. However, if it is a multi-company development of a thing, a function may need to tune multiple interfaces, one or two Ajax can be displayed on the JSP page, but if more, you can not write so much Ajax in the front-end. At this time need to encapsulate an interface, in the interface how to call other interfaces? This is the use of the Java.net.URL class.
Java.net.URL usage is as follows
BufferedReader in=NULL; Java.net.HttpURLConnection Conn=NULL; String msg= "";//Save response Information after invoking the HTTP service Try{
//Instantiate URL java.net.URL URL=NewJava.net.URL (path);
//Get httpurlconnection conn by URL =(java.net.HttpURLConnection) url.openconnection ();
//Set the requested parameter Conn.setrequestmethod ("POST"); Conn.setconnecttimeout (5 * 1000);//Set the connection time-out to 5 secondsConn.setreadtimeout (20 * 1000);//set the read time-out to 20 seconds conn.setdooutput (true); //use a URL connection for output, set the DOOUTPUT flag to TrueConn.setdoinput (true); Conn.setrequestproperty ("Content-type", "Text/xml;charset=utf-8"); //conn.setrequestproperty ("content-encoding", "gzip");Conn.setrequestproperty ("Content-length", String.valueof (Params.length ())); //Set request content (length) length OutputStream OutStream= Conn.getoutputstream ();//returns the output stream written to this connectionOutstream.write (Params.getbytes ()); //writes parameters to the stream outstream.close ();//Close the stream if(Conn.getresponsecode () = = 200) { //HTTP Service side return encoding is UTF-8, it must be set to UTF-8, keep the encoding uniform, otherwise there will be garbled in Chinesein =NewBufferedReader (NewInputStreamReader (InputStream) Conn.getinputstream (),"UTF-8")); Msg=In.readline (); } }Catch(Exception ex) {ex.printstacktrace (); }finally { if(NULL!=In ) {In.close (); } if(NULL!=conn) {Conn.disconnect (); } } returnMsg
Java sends HTTP request call interface via Java.net.URL