Httpclient is not a browser, but a client HTTP transmission class library. Httpclient is used to transmit and receive HTTP messages. Two important classes are used in the httpclient module: httpget and httppost. These two classes are used to submit httpget and httppost requests respectively.
Next we will use the above theory as the basis, and then conduct a connection http://www.ip138.com/ips138.aspquery ip practice:
First, we need the following jar package:
httpclient-4.2.jarhttpclient-cache-4.2.jarhttpcore-4.2.jarhttpmime-4.2.jarcommons-logging-1.1.jar
The source code of my IP address query is as follows:
Package COM. java; import Java. io. ioexception; import Org. apache. HTTP. httpentity; import Org. apache. HTTP. httpresponse; import Org. apache. HTTP. client. methods. httpget; import Org. apache. HTTP. impl. client. defaulthttpclient; import Org. apache. HTTP. util. entityutils; import org.html parser. nodefilter; import org.html parser. parser; import org.html parser. filters. tagnamefilter; import org.html parser. util. nodelist; Public Class iptest {public static string ip2addr (string IP) throws exception {defaulthttpclient httpclient = new defaulthttpclient (); string html = ""; try {httpget = NULL; // create httpget object httpget = new httpget ("http://www.ip138.com/ips138.asp? IP = "+ IP +" & Action = 2 "); // use the execute method to send an httpget request and return the httpresponse object httpresponse response = httpclient.exe cute (httpget ); // use the getentity method to obtain the returned result httpentity entity = response. getentity (); // read response content html = entityutils. tostring (entity, "gb2312"); // close the bottom layer entityutils. consume (entity);} catch (ioexception e) {Throw E;} finally {httpclient. getconnectionmanager (). shutdown ();}/*** parses HTML using Parser, stores the content under the tag <li> In nodelist, and obtains the content under the first <li>, the final result obtained after split is Japan */parser myparser = parser. createparser (HTML, "gb2312"); nodefilter filter = new tagnamefilter ("Li"); nodelist = myparser. parse (filter); system. out. println (nodelist); string result = nodelist. elementat (0 ). toplaintextstring (); system. out. println (result); string address = result. split (":") [1]; return address;} public static void main (string [] ARGs) {try {ip2addr ("111.111.111.111");} catch (exception E) {system. out. println ("network exception ");}}}
Program Execution result: Japan, it can be seen that 111.111.111 is a Japanese IP address.