The Java background call HttpURLConnection class simulates the browser request instance of of that can be used for interface calls

  • 2020-04-01 03:32:38
  • OfStack

In general, it is inevitable to encounter the call of the external interface in the project development. This article illustrates the method of the Java background call HttpURLConnection class to simulate the browser request. Can be used for interface calls. Share with you for your reference. The specific implementation method is as follows:

package com.cplatform.movie.back.test;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder; public class HttpURLConnectionTest {
    public static final String GET_URL = "http://112.4.27.9/mall-back/if_user/store_list?storeId=32";
    public static final String POST_URL = "http://112.4.27.9/mall-back/if_user/store_list";
   
    /**
     * Interface call GET
     */
    public static void httpURLConectionGET() {
        try {
            URL url = new URL(GET_URL);    //Converts the string to the URL request address
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();//Open the connection
            connection.connect();//Connection session
            //Gets the input stream
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {//Loop read flow
                sb.append(line);
            }
            br.close();//Close the stream
            connection.disconnect();//Disconnect
            System.out.println(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(" failure !");
        }
    }
   
    /**
     * Interface call   POST
     */
    public static void httpURLConnectionPOST () {
        try {
            URL url = new URL(POST_URL);
           
            //Url connection  that returns the url in the open method; Strong connection to HttpURLConnection & PI; (identifies the remote object connection referenced by a url)
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();//At this time, cnnection is just a connection object,
in the connection            
            //Set the connection output stream to true, with the default false (the post request is an implicitly passed parameter in the form of a stream)
            connection.setDoOutput(true);
           
            //Set the connection input stream to true
            connection.setDoInput(true);
           
            //Set the request mode to post
            connection.setRequestMethod("POST");
           
            //The post request cache is set to false
            connection.setUseCaches(false);
           
            //Sets whether the HttpURLConnection instance automatically redirects
            connection.setInstanceFollowRedirects(true);
           
            //Set the properties in the header of the request (the following is the type of setting content, set to a urlEncoded from parameter)
            //Application/x - javascript text/XML -> XML data application/x - javascript -> Application/json object x - WWW - form - urlencoded -> Form data
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
           
            //Connect (request did not start until the connection. The getInputStream () method call, when each parameter is set above) should be carried out before this method < br / >             connection.connect();
           
            //Creates an input/output stream that outputs the parameters to the connection.
            DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());
            String parm = "storeId=" + URLEncoder.encode("32", "utf-8"); //URLEncoder. Encode () method   Encode the string
           
            //Output the parameter to the connection
            dataout.writeBytes(parm);
           
            //When the output is complete, refresh and close the stream
            dataout.flush();
            dataout.close(); //Important and easily ignored steps (close the stream, remember!) < br / >            
            System.out.println(connection.getResponseCode());
           
            //Connect to initiate the request, process the server response & NBSP; (from the connection to the input stream and wrapped as bufferedReader)
            BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder sb = new StringBuilder(); //Used to store response data
           
            //Loop reads the stream until the end
            while ((line = bf.readLine()) != null) {
                sb.append(bf.readLine());
            }
            bf.close();    //Important and easily ignored steps (close the stream, remember!) < br / >             connection.disconnect(); //Destroy connection
            System.out.println(sb.toString());
   
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
   
    public static void main(String[] args) {
//        httpURLConectionGET();
        httpURLConnectionPOST();
    }
}

I hope this article has been helpful to your Java programming.


Related articles: