LZ in the project encountered need to test whether the remote address connectivity needs, research, and finally done. Share with you.
2 jar packs (Httpclient-4.3.1.jar and Httpcore-4.3.jar) are required and can be imported into the Web engineering lib directory. Jar package can be downloaded in the official website http://hc.apache.org/downloads.cgi, another can download the source package, which contains many classic examples, can be reference and learning.
Package com.williamwu.service;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import org.apache.http.HttpEntity;
Import Org.apache.http.client.methods.CloseableHttpResponse;
Import Org.apache.http.client.methods.HttpGet;
Import org.apache.http.impl.client.CloseableHttpClient;
Import org.apache.http.impl.client.HttpClients; public class Httpclienttest {/** * * Test URL connectivity and obtain content * * @author WILLIAMWU * @since 2013-11-27 * @pa Ram Test URL * @return Return request Content * */public static String connectedtest (String url) throws IOException {//Closeab
Lehttpclient httpclient = Httpclients.createdefault ();
StringBuffer content = new StringBuffer ();
try {httpget httpget = new HttpGet (URL);
Closeablehttpresponse response = Httpclient.execute (HttpGet);
Output return status code successful return: http/1.1 OK,//judge whether the string contains "200" to indicate the success of the test Connection System.out.println (Response.getstatusline ()); Httpentity Entity = Response.getentity ();
if (null = = entity) {return "";
} InputStream in = Entity.getcontent ();
try {bufferedreader buffer = new BufferedReader (new InputStreamReader (in, "Utf-8"));
String line = null;
while (the null!= (line = Buffer.readline ())) {content.append (line);
finally {response.close ();
In.close ();
finally {httpclient.close ();
return content.tostring ();
public static void Main (string[] args) {try {System.out.println (connectedtest ("http://www.csdn.net"));
catch (IOException e) {e.printstacktrace (); }
}
}