杨子刚的博客


Android网络请求实践

2015-01-28

在代码中使用HttpClient来执行网络请求,使用ThreadRunnable在单独线程内调用HttpClient,使用Handler来向调用者传递请求失败、请求完成等信息。代码来自于 Async HTTP Connection on Android

  1 package edu.gvsu.masl.asynchttp;
  2  
  3 import java.io.*;
  4  
  5 import org.apache.http.*;
  6 import org.apache.http.client.*;
  7 import org.apache.http.client.methods.*;
  8 import org.apache.http.entity.*;
  9 import org.apache.http.impl.client.DefaultHttpClient;
 10 import org.apache.http.params.HttpConnectionParams;
 11  
 12 import android.graphics.*;
 13 import android.os.*;
 14  
 15 /**
 16  * Asynchronous HTTP connections
 17  *
 18  * @author Greg Zavitz & Joseph Roth
 19  */
 20 public class HttpConnection implements Runnable {
 21  
 22     public static final int DID_START = 0;
 23     public static final int DID_ERROR = 1;
 24     public static final int DID_SUCCEED = 2;
 25  
 26     private static final int GET = 0;
 27     private static final int POST = 1;
 28     private static final int PUT = 2;
 29     private static final int DELETE = 3;
 30     private static final int BITMAP = 4;
 31  
 32     private String url;
 33     private int method;
 34     private Handler handler;
 35     private String data;
 36  
 37     private HttpClient httpClient;
 38  
 39     public HttpConnection() {
 40         this(new Handler());
 41     }
 42  
 43     public HttpConnection(Handler _handler) {
 44         handler = _handler;
 45     }
 46  
 47     public void create(int method, String url, String data) {
 48         this.method = method;
 49         this.url = url;
 50         this.data = data;
 51         ConnectionManager.getInstance().push(this);
 52     }
 53  
 54     public void get(String url) {
 55         create(GET, url, null);
 56     }
 57  
 58     public void post(String url, String data) {
 59         create(POST, url, data);
 60     }
 61  
 62     public void put(String url, String data) {
 63         create(PUT, url, data);
 64     }
 65  
 66     public void delete(String url) {
 67         create(DELETE, url, null);
 68     }
 69  
 70     public void bitmap(String url) {
 71         create(BITMAP, url, null);
 72     }
 73  
 74     public void run() {
 75         handler.sendMessage(Message.obtain(handler, HttpConnection.DID_START));
 76         httpClient = new DefaultHttpClient();
 77         HttpConnectionParams.setSoTimeout(httpClient.getParams(), 25000);
 78         try {
 79             HttpResponse response = null;
 80             switch (method) {
 81             case GET:
 82                 response = httpClient.execute(new HttpGet(url));
 83                 break;
 84             case POST:
 85                 HttpPost httpPost = new HttpPost(url);
 86                 httpPost.setEntity(new StringEntity(data));
 87                 response = httpClient.execute(httpPost);
 88                 break;
 89             case PUT:
 90                 HttpPut httpPut = new HttpPut(url);
 91                 httpPut.setEntity(new StringEntity(data));
 92                 response = httpClient.execute(httpPut);
 93                 break;
 94             case DELETE:
 95                 response = httpClient.execute(new HttpDelete(url));
 96                 break;
 97             case BITMAP:
 98                 response = httpClient.execute(new HttpGet(url));
 99                 processBitmapEntity(response.getEntity());
100                 break;
101             }
102             if (method < BITMAP)
103                 processEntity(response.getEntity());
104         } catch (Exception e) {
105             handler.sendMessage(Message.obtain(handler,
106                     HttpConnection.DID_ERROR, e));
107         }
108         ConnectionManager.getInstance().didComplete(this);
109     }
110  
111     private void processEntity(HttpEntity entity) throws IllegalStateException,
112             IOException {
113         BufferedReader br = new BufferedReader(new InputStreamReader(entity
114                 .getContent()));
115         String line, result = "";
116         while ((line = br.readLine()) != null)
117             result += line;
118         Message message = Message.obtain(handler, DID_SUCCEED, result);
119         handler.sendMessage(message);
120     }
121  
122     private void processBitmapEntity(HttpEntity entity) throws IOException {
123         BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
124         Bitmap bm = BitmapFactory.decodeStream(bufHttpEntity.getContent());
125         handler.sendMessage(Message.obtain(handler, DID_SUCCEED, bm));
126     }
127  
128 }
 1 package edu.gvsu.masl.asynchttp;
 2  
 3 import java.util.ArrayList;
 4  
 5 /**
 6  * Simple connection manager to throttle connections
 7  *
 8  * @author Greg Zavitz
 9  */
10 public class ConnectionManager {
11      
12     public static final int MAX_CONNECTIONS = 5;
13  
14     private ArrayList<Runnable> active = new ArrayList<Runnable>();
15     private ArrayList<Runnable> queue = new ArrayList<Runnable>();
16  
17     private static ConnectionManager instance;
18  
19     public static ConnectionManager getInstance() {
20         if (instance == null)
21             instance = new ConnectionManager();
22         return instance;
23     }
24  
25     public void push(Runnable runnable) {
26         queue.add(runnable);
27         if (active.size() < MAX_CONNECTIONS)
28             startNext();
29     }
30  
31     private void startNext() {
32         if (!queue.isEmpty()) {
33             Runnable next = queue.get(0);
34             queue.remove(0);
35             active.add(next);
36  
37             Thread thread = new Thread(next);
38             thread.start();
39         }
40     }
41  
42     public void didComplete(Runnable runnable) {
43         active.remove(runnable);
44         startNext();
45     }
46  
47 }