The previous article describes some simple examples of httpclient, and this article continues to demonstrate the functionality of httpclient in a sample way.
In the project we may encounter situations in which, in order to ensure the security of the system, only specific agents are allowed to be accessed, and when interacting with httpclient, they can only be configured with proxies.
Here we use the Goagent proxy to access the face book to simulate this situation. Facebook has been blocked for some reason and can only be accessed through a proxy, so it just fits our present presentation needs. Access is now available on the browser:
You can see the way Facebook is using HTTPS, and the site's certificate is not trusted by the client. So we're going to use HTTPS in a way that "bypasses certificate validation." How to set up the agent, the official website has relevant examples. I use the official website to provide a slightly different, the specific code is as follows:
/** * Set Agent * @param builder * @param hostorip * @param port */public static Httpclientbuilder proxy (String hostorip, int p ORT) {///In turn, proxy address, proxy port number, protocol type Httphost proxy = new Httphost (Hostorip, Port, "http"); Defaultproxyrouteplanner Routeplanner = new Defaultproxyrouteplanner (proxy); return Httpclients.custom (). Setrouteplanner (Routeplanner);}
The return value is Httpclientbuilder, which is used to generate the HttpClient object, and you can set various parameters, where the return value is provided in order to continue configuring SSL after the agent is configured. Open goagent to see proxy IP settings
Now modify the Send method:
/** * Impersonation Request * * @param URL Resource address * @param map parameter list * @param encoding code * @return * @throws nosuchalgorithmexception * @throw S keymanagementexception * @throws IOException * @throws clientprotocolexception */public static string send (string URL , map<string,string> map,string encoding) throws Keymanagementexception, NoSuchAlgorithmException, Clientprotocolexception, IOException {String BODY = "";//Bypass certificate validation, process HTTPS requests sslcontext Sslcontext = Createignoreverifyssl (); Set protocol HTTP and HTTPS for the processing of the socket-Link Factory object registry<connectionsocketfactory> socketfactoryregistry = Registrybuilder . <connectionsocketfactory>create (). Register ("http", plainconnectionsocketfactory.instance). R Egister ("https", new Sslconnectionsocketfactory (Sslcontext)). Build (); Poolinghttpclientconnectionmanager Connmanager = new Poolinghttpclientconnectionmanager (socketFactoryRegistry); Httpclients.custom (). Setconnectionmanager (Connmanager); Create a customThe HttpClient object Closeablehttpclient client = Proxy ("127.0.0.1", 8087). Setconnectionmanager (Connmanager). build ();// Closeablehttpclient client = Httpclients.createdefault ();//Create Post Method Request Object HttpPost HttpPost = new HttpPost (URL);// Filling parameters list<namevaluepair> Nvps = new arraylist<namevaluepair> (), if (Map!=null) {for (entry<string, String > Entry:map.entrySet ()) {Nvps.add (New Basicnamevaluepair (Entry.getkey (), Entry.getvalue ()));}} Set parameters to the Request object in Httppost.setentity (new Urlencodedformentity (Nvps, encoding)); SYSTEM.OUT.PRINTLN ("Request address:" +url); SYSTEM.OUT.PRINTLN ("Request parameter:" +nvps.tostring ());//Set header information//Specify Header "Content-type", "User-agent" Httppost.setheader (" Content-type "," application/x-www-form-urlencoded "); Httppost.setheader (" User-agent "," mozilla/4.0 (compatible; MSIE 5.0; Windows NT; Digext),//Perform the request operation and get the result (synchronous blocking) closeablehttpresponse response = Client.execute (HttpPost);//Get result entities httpentity entity = Response.getentity (); if (entity! = NULL) {//by specifying the encoding to convert the result entity to String type BODY = entityutils.tostring (Entity, encoding);} Entityutils.consume (entity);//Release link response.close (); return body;}
The test code is as follows:
public static void Main (string[] args) throws ParseException, IOException, Keymanagementexception, Nosuchalgorithmexception{string url = "https://www.facebook.com/"; String BODY = send (URL, null, "Utf-8"); SYSTEM.OUT.PRINTLN ("Transaction response results"); System.out.println (body);}
after running, the result:
Sure enough you can access it successfully.
Okay, so here's the basic tutorial, the next one I'm going to encapsulate is a tool class that I think is a lot more powerful than the package class for sharing on the web, so please look forward to it.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced. If you want to reprint please declare: "Transfer from http://blog.csdn.net/xiaoxian8023"
Easily play with HttpClient's setup agent to access Facebook