Generally, it is inevitable to encounter calls to external interfaces during project development. This article describes the method of calling the HttpURLConnection class in the java background to simulate browser requests. Can be used for interface calls. Share it with everyone for your reference. The specific implementation method is as follows:
Copy the code 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 calls GET
*/
public static void httpURLConectionGET() {
try {
URL url = new URL(GET_URL); // Convert the string into a URL request address
HttpURLConnection connection = (HttpURLConnection) url.openConnection();//Open the connection
connection.connect();//Connect session
// Get input stream
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {// Loop reading stream
sb.append(line);
}
br.close();//Close the stream
connection.disconnect(); // Disconnect
System.out.println(sb.toString());
} catch (Exception e) {
e.printStackTrace();
System.out.println("Failed!");
}
}
/**
* Interface calls POST
*/
public static void httpURLConnectionPOST () {
try {
URL url = new URL(POST_URL);
//Force the urlConnection connection returned by the open method to an HttpURLConnection connection (identify a remote object connection referenced by the url)
HttpURLConnection connection = (HttpURLConnection) url.openConnection();// At this time cnnection is just a connection object, waiting to be connected
//Set the connection output stream to true, the default is false (post requests implicitly pass parameters in the form of a stream)
connection.setDoOutput(true);
//Set the connection input stream to true
connection.setDoInput(true);
//Set the request method to post
connection.setRequestMethod("POST");
// post request cache is set to false
connection.setUseCaches(false);
//Set whether the HttpURLConnection instance automatically performs redirection
connection.setInstanceFollowRedirects(true);
//Set each attribute in the request header (the following is the type of content, set to the from parameter encoded by urlEncoded)
// application/x-javascript text/xml->xml data application/x-javascript->json object application/x-www-form-urlencoded->form data
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// Establish a connection (the request is not started until the connection.getInputStream() method is called. The above parameter settings need to be done before this method)
connection.connect();
//Create an input and output stream, used to output the parameters carried in the connection, (the output content is the content after?)
DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());
String parm = "storeId=" + URLEncoder.encode("32", "utf-8"); //URLEncoder.encode() method encodes strings
// Output parameters to the connection
dataout.writeBytes(parm);
// Refresh and close the stream after output is complete
dataout.flush();
dataout.close(); // Important and easy to ignore step (close the stream, remember!)
System.out.println(connection.getResponseCode());
//The connection initiates a request and processes the server response (obtains the input stream from the connection and wraps it as bufferedReader)
BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder sb = new StringBuilder(); // Used to store response data
// Read the stream in a loop, if it does not reach the end
while ((line = bf.readLine()) != null) {
sb.append(bf.readLine());
}
bf.close(); // Important and easy to ignore step (close the stream, remember!)
connection.disconnect(); // Destroy the connection
System.out.println(sb.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
// httpURLConectionGET();
httpURLConnectionPOST();
}
}
I hope this article will be helpful to everyone’s Java programming.