Java background calls the HttpURLConnection class simulates a browser request instance (which can be used for interface calls) _java

Source: Internet
Author: User
Tags readline

In general, it is unavoidable to encounter the call of external interface in project development, this article illustrates the method of Java background call HttpURLConnection class to simulate browser request. Can be used for interface calls. Share to everyone for your reference. The implementation methods are as follows:

Copy Code 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 Call Get
*/
public static void Httpurlconectionget () {
try {
URL url = new URL (get_url); Converts a string to a URL request address
HttpURLConnection connection = (httpurlconnection) url.openconnection ();//Open connection
Connection.connect ();//Connection session
Get input stream
BufferedReader br = new BufferedReader (New InputStreamReader (Connection.getinputstream ()));
String Line;
StringBuilder sb = new StringBuilder ();
while (line = Br.readline ())!= null) {//loop read stream
Sb.append (line);
}
Br.close ();//Close 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);

Converts a URL with a urlconnection connection returned by the open method to a HttpURLConnection connection (identifies a remote object connection referenced by a URL)
HttpURLConnection connection = (httpurlconnection) url.openconnection ()//At this point cnnection is only a connection object, to be connected

Sets the connection output stream to True, default false (post requests are implicitly passed parameters in the form of a stream)
Connection.setdooutput (TRUE);

Set connection input stream to True
Connection.setdoinput (TRUE);

Set the request mode to post
Connection.setrequestmethod ("POST");

Post request cache set to False
Connection.setusecaches (FALSE);

Sets whether the HttpURLConnection instance automatically performs redirection
Connection.setinstancefollowredirects (TRUE);

Set the properties within the request header (the following is the type of the content to set to the urlencoded encoded from parameter)
Application/x-javascript text/xml->xml Data Application/x-javascript->json objects application/ x-www-form-urlencoded-> form data
Connection.setrequestproperty ("Content-type", "application/x-www-form-urlencoded");

Establish a connection (the request did not start until the Connection.getinputstream () method call was initiated, and the above parameter settings need to be preceded by this method)
Connection.connect ();

Creates an input-output stream that is used to output the parameters to the connection, (the output is the following.)
DataOutputStream dataout = new DataOutputStream (Connection.getoutputstream ());
String parm = "storeid=" + Urlencoder.encode ("A", "utf-8"); The Urlencoder.encode () method encodes a string

Output parameters to a connection
Dataout.writebytes (Parm);

Refresh and close the stream when the output is complete
Dataout.flush ();
Dataout.close (); Important and easy to ignore steps (close the stream, remember!)

System.out.println (Connection.getresponsecode ());

The connection initiates the request, processes the server response (obtains from the connection to the input stream and wraps as BufferedReader)
BufferedReader bf = new BufferedReader (New InputStreamReader (Connection.getinputstream ()));
String Line;
StringBuilder sb = new StringBuilder (); Used to store response data

Loop read stream, if not at the end
while (line = Bf.readline ())!= null) {
Sb.append (Bf.readline ());
}
Bf.close (); Important and easy to ignore steps (close the stream, remember!)
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 will help you with your Java programming.

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.