First, using resttemplate to achieve
Resttemplate is a request class in the Spring-web package that can basically meet the general business requirements.
private static Resttemplate resttemplate = new Resttemplate ();
public static final httpheaders Jsonandxml;
static {
Jsonandxml = new Httpheaders ();
Jsonandxml.setcontenttype (Mediatype.application_json_utf8);
list<mediatype> mediatypelist = new arraylist<mediatype> ();
Mediatypelist.add (mediatype.application_xml);
Jsonandxml.setaccept (mediatypelist);
}
>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>>>>>>>>>>>>
String response = Resttemplate.exchange (URL, httpmethod.get, new httpentity<> (Jsonandxml), String.class). GetBody ();
In addition to Exchange, Resttemplate has many interfaces for developers to invoke, such as pass-path variables, parameters, and so on.
Second, the use of Apache httpcomponents components to achieve
1. Guide Package
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId> httpclient</artifactid>
<version>4.5.1</version>
</dependency>
2. To achieve
Httpentity BODY = new Stringentity (new Gson (). Tojson (Root), contenttype.create ("Application/json", Consts.utf_8));
Defaultbhttpclientconnection conn = null; try {httpprocessor httpprocessor = Httpprocessorbuilder.create (). Add (New Requestcontent ()). Add (New Requesttar GetHost ()). Add (New Requestconncontrol ()). Add (New Requestuse
Ragent ("test/1.1")). Add (New Requestexpectcontinue (True)). Build ();
Httprequestexecutor httprequestexecutor = new Httprequestexecutor ();
Httpcorecontext corecontext = new Httpcorecontext ();
Httphost host = new Httphost (host, PORT);
Corecontext.settargethost (host);
conn = new Defaultbhttpclientconnection (8 * 1024);
Connectionreusestrategy connectionreusestrategy = defaultconnectionreusestrategy.instance; if (!conn.isopen ()) {Socket socket = new Socket (Host.gethostname (), hoSt.getport ());
Conn.bind (socket);
Basichttpentityenclosingrequest request = new Basichttpentityenclosingrequest ("POST", url);
Request.setentity (body);
System.out.println ("URL:" + request.getrequestline (). GetURI ());
Httprequestexecutor.preprocess (Request, Httpprocessor, corecontext);
HttpResponse response = Httprequestexecutor.execute (Request, Conn, corecontext);
Httprequestexecutor.postprocess (response, Httpprocessor, corecontext);
SYSTEM.OUT.PRINTLN ("Response:" + response.getstatusline ());
SYSTEM.OUT.PRINTLN ("The body of the response" + entityutils.tostring (response.getentity ()));
System.out.println ("= = = = = = = End = =");
if (!connectionreusestrategy.keepalive (response, Corecontext)) Conn.close ();
else System.out.println ("Keep link");
catch (Exception e) {e.printstacktrace (); Finally {try {conn.close ();
catch (IOException e) {e.printstacktrace ();
}
}