Project requirements: Implement a POST request, and the request format is in JSON format.
Maven Dependency Packages
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactid>httpclient</ artifactid> <version>4.5.3</version> </dependency> <dependency> <groupId> Commons-httpclient</groupid> <artifactId>commons-httpclient</artifactId> <version>3.1 </version> </dependency>
Java Code Implementation:
Httpclient httpclient = new httpclient (); Httpclient.getparams (). SetContentCharset ("UTF-8") ; Postmethod method = new postmethod (URL); string str = "{\ r \ n" + "\" begindate\ ": \" 2017-11-01\ ", \ r \ n" + "\" enddate\ ": \" 2017-11-01\ "\ r \ n" + "}"; Requestentity entity = new stringrequestentity (str, "Application/json", "UTF-8"); Method.setrequestentity (entity); Httpclient.executemethod (method);inputstream in = Method.getresponsebodyasstream ();//Convert stream to Stringstringbuffer sb = new stringbuffer () below ; Inputstreamreader isr = new inputstreamreader (in, "UTF-8"); char[] b = new char[4096];for (int n; (N = isr.read (b)) != -1;) { sb.append (new string (b, 0, n)); } stRing returnstr = sb.tostring (); system.out.println (RETURNSTR);
This article from "a Program of self-cultivation" blog, reproduced please contact the author!
Java Implementation POST request (Postmethod)