This is a time to use spring boot, it is really very convenient to remove the cumbersome copy files to build the problem of the project.
During this time encountered a problem to request another server interface, the first is to use the HTTP client to request, but personally feel very troublesome. So I tried to resttemplate the service provider's application. Unexpected is also able to request success, the principle of which I still do not know. Ha ha
No more nonsense. Paste the Sample code:
Get Request Example:
We assume that a request to obtain an IP address is the interface of that region: http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=218.4.255.255
public static void Main (string[] args) {
resttemplate resttemplate = new Resttemplate ();
String jsonstr = resttemplate.getforentity ("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format={0}&ip= {1} ", String.class," json "," 218.4.255.255 "). GetBody ();
System.out.println (JSONSTR);
}
Look at that. A simple get request is done, and no other toolkit has been introduced.
Post Request Example:
A POST request can be a bit cumbersome, assuming that a form is requested with the name and age parameters
public static void Main (string[] args) throws jsonprocessingexception {
resttemplate resttemplate = new Resttemplate ( );
Httpheaders headers = new Httpheaders ();
The request header is set
headers.setcontenttype (mediatype.application_form_urlencoded);
Objectmapper mapper = new Objectmapper ();
Map<string, string> params= maps.newhashmap ();
Params.put ("name", "Small Week");
Params.put ("Age", "a");
String value = mapper.writevalueasstring (params);
httpentity<string> requestentity = new Httpentity<string> (value, headers); Execute HTTP request
responseentity<string> response = resttemplate.postforentity ("Post_url", requestentity , string.class);
System.out.println (Response.getbody ());
}
In fact, the use of Resttemplate request is very convenient. I hope that we can try Oh.