In the afternoon, the code for the HTTP request in the company was refactored, and each of the previous requests needed to write a post method, not the same as the requested parameter. And there's a lot of cumbersome code in the code, like every request needs a new defaulthttpclient, In finally, each time need to shutdown. A previous read of a refactoring book also mentions the stink of such a code. So this afternoon, the previous code was refactored and based on Apache HttpClient official website has written a single example of the Defaulthttpclient class. The single example class is as follows:
Import org.apache.http.HttpEntity;
Import Org.apache.http.HttpResponse;
Import org.apache.http.HttpVersion;
Import org.apache.http.client.HttpClient;
Import Org.apache.http.client.methods.HttpGet;
Import Org.apache.http.conn.ClientConnectionManager;
Import Org.apache.http.conn.scheme.PlainSocketFactory;
Import Org.apache.http.conn.scheme.Scheme;
Import Org.apache.http.conn.scheme.SchemeRegistry;
Import Org.apache.http.conn.ssl.SSLSocketFactory;
Import org.apache.http.impl.client.DefaultHttpClient;
Import Org.apache.http.impl.conn.PoolingClientConnectionManager;
Import Org.apache.http.params.BasicHttpParams;
Import Org.apache.http.params.HttpConnectionParams;
Import Org.apache.http.params.HttpParams;
Import Org.apache.http.params.HttpProtocolParams;
Import Org.apache.http.util.EntityUtils; /** * Guarantee HttpClient Use * * @author Administrator */public class Singletonclient {private static final String
CHARSET = "UTF-8";
private static httpclient singlehttpclient; Private SinGletonclient () {} public static synchronized HttpClient gethttpclient () {if (null = = singlehttpclient) {Httppar
AMS params = new Basichttpparams ();
Httpprotocolparams.setversion (params, httpversion.http_1_1);
Httpprotocolparams.setcontentcharset (params, CHARSET);
Httpprotocolparams.setuseexpectcontinue (params, true); Httpprotocolparams. Setuseragent (params, "mozilla/5.0" (Windows; U Windows NT 5.1; ZH-CN;
rv:1.9.1.5) gecko/20091102 firefox/3.5.5 GTB6 (. NET CLR 3.5.30729) ");
/* Connection Timeout * * Httpconnectionparams.setconnectiontimeout (params, 2000);
/* Request Timeout * * Httpconnectionparams.setsotimeout (params, 4000);
Set HttpClient supported request mode Schemeregistry Schreg = new Schemeregistry ();
Schreg.register (New Scheme ("http", Plainsocketfactory. Getsocketfactory ());
Schreg.register (New Scheme ("https", 443, sslsocketfactory. Getsocketfactory ()); In the latest version of HttpClient, Threadsafeclientconnmanager has been @deprecated out, using PoolingclientconNectionmanager.
Clientconnectionmanager conmgr = new Poolingclientconnectionmanager (Schreg);
Singlehttpclient = new Defaulthttpclient (conmgr, params);
return singlehttpclient; Static Class Testthread extends Thread {@Override public void run () {try {System.out.println) (Gethttpclie
NT ());
HttpResponse response = Gethttpclient (). Execute (New HttpGet ("http://www.baidu.com"));
httpentity entity = response.getentity ();
if (entity!= null) {String x = entityutils.tostring (entity);
System.out.println (x.substring (200, 230));
Ensure the connection can be released back to the manager Entityutils.consume (entity);
} catch (Exception e) {e.printstacktrace ();
}} public static void Main (string[] args) {for (int i = 0; i < i++) {try {thread.sleep (2000);
New Testthread (). Start ();
catch (Interruptedexception e) {e.printstacktrace (); }
}
}
}
Multiple threads are tested to see that the defaulthttpclient bytecode is the same. So this ensures that we have only one defaulthttpclient in the entire application.
The following code is the code after the request was refactored:
@SuppressWarnings ("unchecked") public static Object post (String URL, Object object) {object o = null;
if (url = null | | url.length () <= 0) throw new serviceexception ("URL can not be null.");
url = base_url + URL;
String temp = url.tolowercase ();
if (!temp.startswith ("http://") &&!temp.startswith ("https://")) url = "http://" + url;
url = uri.create (URL). toasciistring ();
Defaulthttpclient httpclient = (defaulthttpclient) singletonclient.gethttpclient ();
try {httppost HttpMethod = new HttpPost (URL);
Httpmethod.setheader ("Key", "********"); If (object instanceof Map) {inputstreamentity reqentity = new Inputstreamentity (Streams. Wrap (Json.tojson
T). GetBytes ("UTF-8")),-1);
Reqentity.setcontenttype ("Binary/octet-stream");
Reqentity.setchunked (TRUE);
Reqentity.setcontentencoding ("UTF-8");
Httpmethod.setentity (reqentity); else if (String.class.isAssignableFrom (Object.getclass ())) {httpmethod.setentity (new Stringentity (Json.tojson (object. toString ()));
else {throw new serviceexception ("Illegal request arguments");
} HttpResponse response = Httpclient.execute (HttpMethod);
int Status=response.getstatusline (). Getstatuscode ();
if (status!= Org.apache.http.HttpStatus.SC_OK) {log.warn ("http satus:" + status + ", url:" + URL); if (Status >= && status <) throw new IOException ("Remote service<" + URL + "> Resp
OSE a error, Status: "+ status";
return null;
} httpentity entity = Response.getentity ();
o = entityutils.tostring (entity);
Entityutils.consume (entity);
catch (Exception e) {throw new Serviceexception ("error!");
finally {//httpclient.getconnectionmanager (). Shutdown ();
return o; }
In the code above, JSON parsing uses the JSON class in the Nutz framework (performance is no less than Google's Gson). This code now only supports requests for map,string type parameters. Later, if there is a need for refactoring. For the time being, it is possible to respond to demand. We just need to pass the past. Object or string in another project for database lookup validation. Only need to get the request to succeed in this project