In recent projects, it is necessary to send the message through the form of the middleware through the HTTP request to the third party, so the use of the HTTP protocol, the small series took one hours. For post and get requests in the HTTP protocol, a tool class is encapsulated. Here's a little bit of sharing with you.
If there is a bad place please do not hesitate to enlighten me.
/** * @FileName: Httptest.java * @Package: Com.io * @Description: TODO * @author: LUCKY * @date: January 6, 2016 Afternoon 3:49:28 * @version V1.0 */package com.io;import java.io.ioexception;import java.io.inputstreamreader;import java . Io. Outputstream;import Java.io.unsupportedencodingexception;import Java.net.httpurlconnection;import Java.net.URL; Import Java.net.urlencoder;import Java.security.securerandom;import java.security.cert.CertificateException; Import Java.security.cert.x509certificate;import java.util.hashmap;import Java.util.map;import java.util.Map.Entry ; Import Java.util.set;import Javax.net.ssl.hostnameverifier;import Javax.net.ssl.httpsurlconnection;import Javax.net.ssl.keymanager;import Javax.net.ssl.sslcontext;import Javax.net.ssl.sslsession;import Javax.net.ssl.trustmanager;import javax.net.ssl.x509trustmanager;import com.alibaba.common.lang.stringutil;/** * @ Classname:httptest * @Description: The HTTP connection tool that starts the package itself, the parameters passed by the HTTP connection are encapsulated into an object, * http in the GET request,is to stitch the parameters behind the URL, and the POST request direct output can be * @author: LUCKY * @date: January 6, 2016 PM 3:49:28 */public class Httptest {private static final St Ring Method_post = "POST";p rivate static final String method_get = "GET";p rivate static final String default_charset = "UT F-8 ";p rivate static final string https =" https ";p rivate static final String TLS =" TLS ";p rivate static final string CTYPE = "application/x-www-form-urlencoded;charset=" + default_charset;public static void Main (string[] args) throws Exception {map<string, string> param = new hashmap<string, string> ();p aram.put ("Body", string.valueof ( System.currenttimemillis ()));p aram.put ("tag", "Scatter powder"); String string = Doget ("Http://localhost/receive.do", param,3000, 3000); String AA = DoPost ("Http://localhost/receive.do", param,3000, 3000); System.out.println (String.Length ()); System.out.println (string);} /** * @throws Exception * @Title: DoPost * @Description: DoPost send Request action * @param @param URL * @param @param params * @param @param readtimeout * @param @paRam ConnectTimeout * @param @return * @return String * @throws */public static string doPost (string url, map<string, St ring> params,int readtimeout, int connecttimeout) throws Exception {httpurlconnection connection = Null;outputstream o UT = null; String result = null;try {connection = getconnection (new URL (URL), Readtimeout,connecttimeout, method_post, CTYPE, NULL); byte[] content = new Byte[0]; String param = getUrl (params, default_charset), if (Stringutil.isnotempty (param)) {content = Param.getbytes (default_ CHARSET);} out = Connection.getoutputstream ();//post transmits message contents Out.write (content);//Accept the return value through buffer to accept result = responseasstring ( connection);} catch (IOException e) {e.printstacktrace (); throw e;} finally {if (connection! = null) {Connection.disconnect ();}} return result;} /** * @Title: Doget * @Description: Doget Send Message request * @param @param URL * @param @param params * @param @param readtimeout * @ Param @param connecttimeout * @param @return * @return String * @throws */public static stringDoget (String URL, map<string, string> params,int readtimeout, int connecttimeout) {HttpURLConnection connection = n Ull String Result=null;try {string query = GetUrl (params, default_charset); connection = getconnection (new URL (buildurl (URL, Query)), ReadTimeout, ConnectTimeout, method_get, CTYPE, NULL); Result=responseasstring (connection);} catch (Exception e) {e.printstacktrace ();} finally {if (connection! = null) {Connection.disconnect ();}} return result;} The Doget and Dopost request the final acceptance of the reference to extract the private static String responseasstring (HttpURLConnection connection) {StringBuffer Buffer = new StringBuffer (); InputStreamReader reader = Null;outputstream out = null;try {//Assuming a successful return if (httpurlconnection.ht TP_OK = = Connection.getresponsecode ()) {reader = new InputStreamReader (Connection.getinputstream ()); char[] ch = new Char [1024];int x = 0;while ((x = Reader.read (ch))! =-1) {buffer.append (ch, 0, x);}}} catch (Exception e) {e.printstacktrace ();} finally {if (connection! = null) {Connection.disConnect ();}} return buffer.tostring ();} Need to write a getconnection method, Dopost and Doget connection to extract the private static httpurlconnection getconnection (URL url, int Readtimeout,int ConnectTimeout, String method, String ctype,map<string, String> headmap) throws Exception { HttpURLConnection connection = null;if (url = = null) {return null;} if (Https.equals (Url.getprotocol ())) {Sslcontext ctx = null;try {ctx = Sslcontext.getinstance (TLS); Ctx.init (new Keymanager[0],new trustmanager[] {new Defaulttrustmanager ()},new securerandom ());} catch (Exception e) {throw new IOException (e);} Httpsurlconnection Connhttps = (httpsurlconnection) url.openconnection (); Connhttps.setsslsocketfactory ( Ctx.getsocketfactory ()); Connhttps.sethostnameverifier (new Hostnameverifier () {public boolean verify (String hostname , SSLsession session) {return true;}}); connection = Connhttps;} else {connection = (HttpURLConnection) url.openconnection ();} Connection.setreadtimeout (readtimeout); Connection.setdoinput (true); connection.seTdooutput (True); Connection.setrequestmethod (method); Connection.setconnecttimeout (ConnectTimeout); Connection.setrequestproperty ("Accept", "text/xml,text/javascript,text/html"); Connection.setrequestproperty (" User-agent "," Top-sdk-java "); Connection.setrequestproperty (" Content-type ", CType);//Traverse settings headmapif (null! = Headmap) {set<entry<string, string>> entries = Headmap.entryset (); for (map.entry<string, string> Entry: Entries) {Connection.setrequestproperty (Entry.getkey (), Entry.getvalue ());}} return connection;} /** * @Title: GETURL * @Description: Doget The URL to be stitched when sending a request * @param @param params * @param @param charset * @param @return * @p Aram @throws Unsupportedencodingexception * @return String * @throws */public static string GetUrl (Map<string, STRING&G T params, String charset) throws Unsupportedencodingexception {StringBuffer buffer = new StringBuffer ("?"); if (params = = null && params.isempty ()) {return null;} Otherwise, start stitching the values that need to be passed. The URL? Aa==bb&cc==ee This similar connection value SET< entry<string, string>> entries = Params.entryset (); for (entry<string, string> entry:entries) {String nam E = Entry.getkey (); String value = Entry.getvalue ();//The need to make an inference is empty, be careful if (Stringutil.isnotempty (name) && Stringutil.isnotempty (value)) {//assumed not to be empty. Start the connection Operation Buffer.append ("&"). Append (name). Append ("="). Append (Urlencoder.encode (value, CharSet));}} Return buffer.tostring (). substring (0, buffer.tostring (). Length ()-1);} /** * @Title: BuildUrl * @Description: Stitching URL address operation * @param @param URL * @param @param query * @param @return * @return Stri ng * @throws */private static string BuildUrl (string url, string query) {if (query = = null && query.isempty ()) {RE Turn URL;} if (Url.endswith ("?")) {url = url + query;} else {url = url + "?"+ Query;} return URL;} private static class Defaulttrustmanager implements X509trustmanager {public x509certificate[] Getacceptedissuers () { return null;} public void checkclienttrusted (x509certificate[] chain, String authtype) throws certificateexception {}public void Checkservertrusted (x509certificate[] chain, String authtype) throws Certificateexception {}}}
For more information about the HTTP protocol, please refer to the HTTP protocol specific explanation
Content-type in the HTTP protocol
Get, POST request to send HTTP in Java