转:http://blog.csdn.net/guolin_blog/article/details/12452307
Android中主要提供了两种方式来进行HTTP操作,HttpURLConnection和HttpClient。
这两种方式都支持HTTPS协议、以流的形式进行上传和下载、配置超时时间、IPv6、以及连接池等功能。
HttpClient
DefaultHttpClient和它的兄弟AndroidHttpClient都是HttpClient具体的实现类,它们都拥有众多的API,而且实现比较稳定,bug数量也很少。
但同时也由于HttpClient的API数量过多,使得我们很难在不破坏兼容性的情况下对它进行升级和扩展,所以目前Android团队在提升和优化HttpClient方面的工作态度并不积极。
HttpURLConnection
HttpURLConnection是一种多用途、轻量极的HTTP客户端,使用它来进行HTTP操作可以适用于大多数的应用程序。虽然HttpURLConnection的API提供的比较简单,但是同时这也使得我们可以更加容易地去使用和扩展它。
哪一种才是最好的?
在Android 2.2版本之前,HttpClient拥有较少的bug,因此使用它是最好的选择。
而在Android 2.3版本及以后,HttpURLConnection则是最佳的选择。它的API简单,体积较小,因而非常适用于Android项目。压缩和缓存机制可以有效地减少网络访问的流量,在提升速度和省电方面也起到了较大的作用。对于新的应用程序应该更加偏向于使用
HttpURLConnection代码:
1 private void checkVersion() {
2 final long startTime = System.currentTimeMillis();
3 new Thread(new Runnable() {
4 @Override
5 public void run() {
6 Message msg = mHandler.obtainMessage();
7 HttpURLConnection conn = null;
8 try {
9 URL url = new URL("http://10.0.2.2:8080/update.json");
10 conn = (HttpURLConnection) url.openConnection();
11 conn.setRequestMethod("GET"); //请求方法为GET
12 conn.setConnectTimeout(5000); //链接超时为5秒
13 conn.setReadTimeout(5000); //读取超时为5秒
14 conn.connect();
15 int responseCode = conn.getResponseCode();
16 if ( responseCode == 200 ) {
17 InputStream inputStream = conn.getInputStream();
18 String result = StreamUtils.readFromStream(inputStream);
19 VersionBean versionBean = parseJsonWithGson(result);
20 mVersionName = versionBean.getVersionName();
21 mDescription = versionBean.getDescription();
22 mVersionCode = versionBean.getVersionCode();
23 mDownLoadUrl = versionBean.getDownLoadUrl();
24 LogUtils.e(TAG, mDownLoadUrl);
25 if ( mVersionCode > getAppVersionCode() ) {
26 msg.what = CODE_UPDATE_INFO;
27 } else {
28 msg.what = CODE_GO_HOME;
29 }
30 }
31 } catch ( MalformedURLException e ) {
32 msg.what = CODE_URL_ERROR;
33 e.printStackTrace();
34 } catch ( IOException e ) {
35 msg.what = CODE_NETWORK_ERROR;
36 e.printStackTrace();
37 } finally {
38 long endTime = System.currentTimeMillis();
39 long timeUsed = endTime - startTime;
40 if ( timeUsed < 2000 ) {
41 try {
42 Thread.sleep(2000 - timeUsed);
43 } catch ( InterruptedException e ) {
44 e.printStackTrace();
45 }
46 }
47 mHandler.sendMessage(msg);
48 if ( conn != null ) {
49 conn.disconnect();
50 }
51 }
52
53 }
54 }).start();
55 }
来源:https://www.cnblogs.com/liyiran/p/5315527.html