HttpURLConnection与 HttpClient 区别/性能测试对比
HttpClient是个开源框架,封装了访问http的请求头,参数,内容体,响应等等,
HttpURLConnection是java的标准类,什么都没封装,用起来太原始,不方便
HttpClient实际上是对Java提供方法的一些封装,
在HttpURLConnection中的输入输出流操作,
在这个接口中被统一封装成了HttpPost(HttpGet)和HttpResponse,
这样,就减少了操作的繁琐性。
性能方面这里做一个测试:
HttpURLConnection VS HttpClient性能测试
版本: HttpURLConnection jdk1.7;HttpClient 4.3
在项目中有一个特别小的相关应用,在选择时做了一下测试,之前先对两个类进行下说明:
HttpURLConnection java的标准类(java.net)
HttpClient Jakarta Commons HttpClient,提供对HTTP协议访问的封装,包括http的请求头,参数,内容体,响应等及多线程的应用。
public class HttpTest { private static String link = "http://www.baidu.com"; public static void main(String[] args) { long a = System.currentTimeMillis(); useHttpURlConnection(); long b = System.currentTimeMillis(); System.out.println("use httpurlconnection: "+(b-a)); long c = System.currentTimeMillis(); useHttpClient(); long d = System.currentTimeMillis(); System.out.println("use httpClient: "+(d-c)); } private static void useHttpClient() { try { HttpClientUtil.get(link, null, null); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void useHttpURlConnection(){ HttpURLConnection conn = null; URL url = null; String result = ""; try { url = new java.net.URL(link); conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(10000); conn.connect(); InputStream urlStream = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(urlStream)); String s = ""; while ((s = reader.readLine()) != null) { result += s; } reader.close(); urlStream.close(); conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch(Exception e){ e.printStackTrace(); } } }
结果很明显示,但是在实际应用中,还是应该根据实际的需求进行取舍。
参考:
http://www.cnblogs.com/langtianya/p/4001499.html
http://xiaowei-qi-epro-com-cn.iteye.com/blog/1973295