Java background calls the HttpURLConnection class to simulate browser requests (generally used for interface calls), httpurlconnection
During project development, it is inevitable that an external interface will be called. Mr. Xiaosheng contacted this class for the first time today and followed the API method. If something is wrong, please correct me and thank you!
1 package com. cplatform. movie. back. test; 2 3 import java. io. bufferedReader; 4 import java. io. dataOutputStream; 5 import java. io. inputStreamReader; 6 import java.net. httpURLConnection; 7 import java.net. URL; 8 import java.net. URLEncoder; 9 10 11 12 public class HttpURLConnectionTest {13 public static final String GET_URL = "http: // 112.4.27.9/mall-back/if_user/store_list? StoreId = 32 "; 14 public static final String POST_URL =" http: // 112.4.27.9/mall-back/if_user/store_list "; 15 16/** 17 * interface call GET 18 */19 public static void httpURLConectionGET () {20 try {21 URL = new url (GET_URL ); // convert the string to the URL request address 22 HttpURLConnection connection = (HttpURLConnection) url. openConnection (); // open connection 23 connection. connect (); // connection session 24 // get input stream 25 BufferedReader br = new BufferedR Eader (new InputStreamReader (connection. getInputStream (); 26 String line; 27 StringBuilder sb = new StringBuilder (); 28 while (line = br. readLine ())! = Null) {// cyclically read the 29 sb stream. append (line); 30} 31 br. close (); // close the stream 32 connection. disconnect (); // disconnect 33 System. out. println (sb. toString (); 34} catch (Exception e) {35 e. printStackTrace (); 36 System. out. println ("failed! "); 37} 38} 39 40/** 41 * interface call POST 42 */43 public static void httpURLConnectionPOST () {44 try {45 URL url = new URL (POST_URL ); 46 47 // convert the url returned by the open method into an HttpURLConnection connection (which identifies the remote object connection referenced by a url) 48 HttpURLConnection connection = (HttpURLConnection) url. openConnection (); // at this time, the cnnection is only a connection object, and 49 50 will be connected. // set the connection output stream to true, the default value is false (the post request implicitly transmits parameters in stream mode) 51 connection. setDoOutput (True); 52 53 // set the connection input stream to true 54 connection. setDoInput (true); 55 56 // set the request method to post 57 connection. setRequestMethod ("POST"); 58 59 // set the post request cache to false 60 connection. setUseCaches (false); 61 62 // sets whether the HttpURLConnection instance automatically performs redirect 63 connection. setInstanceFollowRedirects (true); 64 65 // set each attribute in the Request Header (The following is the type of the set content, set to the from parameter encoded by urlEncoded) 66 // application/x-javascript text/xml-> xml data application/x-PLAIN C Ript-> json object application/x-www-form-urlencoded-> form data 67 connection. setRequestProperty ("Content-Type", "application/x-www-form-urlencoded"); 68 69 // establish a connection (the request has not started until connection. the call of the getInputStream () method is initiated. The preceding parameter settings must be performed before this method.) 70 connection. connect (); 71 72 // create an input/output stream to output parameters to the connection. (The output content is?) 73 DataOutputStream dataout = new DataOutputStream (connection. getOutputStream (); 74 String parm = "storeId =" + URLEncoder. encode ("32", "UTF-8"); // URLEncoder. the encode () method is a string encoded 75 76 // output the parameter to connect 77 dataout. writeBytes (parm); 78 79 // refresh and close the stream 80 dataout after the output is complete. flush (); 81 dataout. close (); // important and easy to ignore steps (close the stream, remember !) 82 83 System. out. println (connection. getResponseCode (); 84 85 // The connection initiates a request to process the Server Response (from the connection to the input stream and packaged as bufferedReader) 86 BufferedReader bf = new BufferedReader (new InputStreamReader (connection. getInputStream (); 87 String line; 88 StringBuilder sb = new StringBuilder (); // used to store the response data 89 90 // read the stream cyclically, if 91 while (line = bf. readLine ())! = Null) {92 sb. append (bf. readLine (); 93} 94 bf. close (); // important and easy to ignore steps (close the stream, remember !) 95 connection. disconnect (); // destroy the 96 System connection. out. println (sb. toString (); 97 98} catch (Exception e) {99 e. printStackTrace (); 100} 101} 102 103 104 public static void main (String [] args) {105 // httpURLConectionGET (); 106 httpURLConnectionPOST (); 107} 108}
JAVA call interface
String sendPost (String jsonStr, String path)
Throws IOException {
Byte [] data = jsonStr. getBytes ();
Java.net. URL url = new java.net. URL (path );
Java.net. HttpURLConnection conn =
(Java.net. HttpURLConnection) url. openConnection ();
Conn. setRequestMethod ("POST ");
Conn. setConnectTimeout (5*1000); // set the connection timeout value to 5 seconds.
Conn. setReadTimeout (20*1000); // you can specify a read timeout value of 20 seconds.
// Set the DoOutput flag to true if the URL is used for output.
Conn. setDoOutput (true );
Conn. setRequestProperty ("Content-Type", "text/xml; charset = UTF-8 ");
// Conn. setRequestProperty ("Content-Encoding", "gzip ");
Conn. setRequestProperty ("Content-Length", String. valueOf (data. length ));
OutputStream outStream = conn. getOutputStream (); // return the output stream written to this connection.
OutStream. write (data );
OutStream. close (); // close the stream
String msg = ""; // Save the response information after the http service is called.
// If the request response code is 200, the request is successful.
If (conn. getResponseCode () = 200 ){
// The encoding returned by the HTTP server is a UTF-8, so it must be set to a UTF-8, to ensure unified encoding, otherwise there will be Chinese garbled characters
BufferedReader in = new BufferedReader (new InputStreamReader (
(InputStream) conn. getInputStream (), "UTF-8 "));
Msg = in. readLine ();
In. close ();
}
Conn. disconnect (); // disconnect
Return msg;
}... Remaining full text>
How does the underlying layer of JAVA program call http Communication? Does it call the operation system interface?
Http is a protocol. If we want to transmit data over a network using http, we must follow this Protocol rule.
Java can use socket for data transmission, but the data format must follow the http protocol.
You can also use encapsulated classes such as URLConnection or HttpURLConnection.
The data is finally sent through the NIC, so the system driver must be called to send the data, but these should be implemented by JVM, Because java is cross-platform, A bridge between java bytecode and the operating system is JVM, and different operating systems correspond to different JVMs. However, these JVMs can be used to parse bytecode and call underlying hardware implementation functions.