网络操作工具类封装,定义两个方法用于上传、下载图片和文字,定义两个内部接口用作网络请求的回调接口 ,定义两个线程类进行网络任务操作

  1 package com.bwf.market.http;
  2 
  3 import java.io.ByteArrayInputStream;
  4 import java.io.ByteArrayOutputStream;
  5 import java.io.DataOutputStream;
  6 import java.io.IOException;
  7 import java.io.InputStream;
  8 import java.net.HttpURLConnection;
  9 import java.net.URL;
 10 import java.util.ArrayList;
 11 import java.util.Map;
 12 
 13 import org.apache.http.HttpEntity;
 14 import org.apache.http.HttpResponse;
 15 import org.apache.http.HttpStatus;
 16 import org.apache.http.client.ClientProtocolException;
 17 import org.apache.http.client.HttpClient;
 18 import org.apache.http.client.entity.UrlEncodedFormEntity;
 19 import org.apache.http.client.methods.HttpGet;
 20 import org.apache.http.client.methods.HttpPost;
 21 import org.apache.http.impl.client.DefaultHttpClient;
 22 import org.apache.http.message.BasicNameValuePair;
 23 import org.apache.http.params.BasicHttpParams;
 24 import org.apache.http.params.HttpConnectionParams;
 25 import org.apache.http.params.HttpParams;
 26 import org.apache.http.util.EntityUtils;
 27 
 28 import com.bwf.market.utils.UtilsDebug;
 29 
 30 import android.graphics.Bitmap;
 31 import android.os.Handler;
 32 import android.os.Message;
 33 import android.util.Log;
 34 /**
 35  * 网络操作工具类封装
 36  * 
 37  * 主要包括:
 38  * 1. 定义两个方法用于上传、下载图片和文字
 39  * 2. 定义两个内部接口用作网络请求的回调接口
 40  * 3. 定义两个线程类进行网络任务操作
 41  * */
 42 public class UtilsHttp {
 43     private static final int MSG_SUCCESSED = 1;                //数据获取成功
 44     private static final int MSG_FAILED = 2;                //数据获取失败
 45     private static final int PIC_UPLOAD_SUCCESSED = 3;        //图片上传成功
 46     private static final int PIC_UPLOAD_FAILED = 4;            //图片上传失败
 47     
 48     private CallBackText callBackText;
 49     private CallBackImage callBackImage;                    //两个回调接口对象
 50     
 51     /**
 52      * 上传或者下载商品文字信息回调接口
 53      * */
 54     public interface CallBackText{
 55         void onSuccess(String result);                        // 成功后返回一个字符串,Jsons数据
 56         void onFailure();
 57     }
 58     
 59     /**
 60      * 上传图片的回调接口
 61      * */
 62     public interface CallBackImage{
 63         void onSuccessImage(String result);                    // 成功后返回一个文字提示信息
 64         void onFailureImage();
 65     }
 66     /**
 67      * 网络任务执行完毕后,收到消息执行网络请求的回调方法
 68      * 
 69      * */
 70     private Handler handler = new Handler(new Handler.Callback() {
 71         
 72         @Override
 73         public boolean handleMessage(Message msg) {
 74             switch (msg.what) {
 75             case MSG_SUCCESSED:
 76                 callBackText.onSuccess(msg.obj.toString());
 77                 break;
 78             case MSG_FAILED:
 79                 callBackText.onFailure();
 80                 break;
 81             case PIC_UPLOAD_SUCCESSED:
 82                 callBackImage.onSuccessImage(msg.obj.toString());
 83                 break;
 84             case PIC_UPLOAD_FAILED:
 85                 callBackImage.onFailureImage();
 86                 break;
 87             }
 88             return false;
 89         }
 90     });
 91     
 92     /**
 93      * 访问网络服务器
 94      * 
 95      * */
 96     public void accessNetServer(String urlStr,String Method,Map<String, String> map,CallBackText callBack){
 97         this.callBackText = callBack;
 98         AccessNetThread httpThread = new AccessNetThread(urlStr,Method,map);
 99         httpThread.start();
100     }
101     
102     private class AccessNetThread extends Thread{
103         private String urlStr;
104         private String Method;
105         private Map<String, String> map;
106         public AccessNetThread(String urlStr,String Method,Map<String, String> map) {
107             this.urlStr = urlStr;
108             this.Method = Method;
109             this.map = map;
110         }
111         @Override
112         public void run() {
113             HttpParams params = new BasicHttpParams();
114             // 请求超时
115             HttpConnectionParams.setSoTimeout(params, 8*1000);
116             // 连接超时
117             HttpConnectionParams.setConnectionTimeout(params, 8*1000);
118             HttpClient httpClient = new DefaultHttpClient(params);
119             HttpGet httpGet = null;
120             HttpPost httpPost = null;
121             HttpResponse response = null;
122             try {
123                 if(Method.equals("GET")){
124                     StringBuffer sb = new StringBuffer(urlStr+"?");
125                     for (Map.Entry<String, String> entry : map.entrySet()) {
126                         sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
127                     }
128                     sb.deleteCharAt(sb.length()-1);
129                     httpGet = new HttpGet(sb.toString());
130                     response = httpClient.execute(httpGet);
131                 }else if(Method.equals("POST")){
132                     httpPost = new HttpPost(urlStr);
133                     // 封装POST请求参数
134                     ArrayList<BasicNameValuePair> localArraylist = new ArrayList<BasicNameValuePair>();
135                     for (Map.Entry<String, String> entry : map.entrySet()) {
136                         localArraylist.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
137                     }
138                     HttpEntity entity = new UrlEncodedFormEntity(localArraylist, "UTF-8");
139                     httpPost.setEntity(entity);
140                     response = httpClient.execute(httpPost);
141                 }
142                 
143                 int code = response.getStatusLine().getStatusCode();
144                 if(code == HttpStatus.SC_OK){
145                     String result = EntityUtils.toString(response.getEntity());
146                     Message msg = handler.obtainMessage(MSG_SUCCESSED, result);
147                     handler.sendMessage(msg);
148                     return;
149                 }
150             } catch (Exception e) {
151                 UtilsDebug.myLog("upload or download exception:"+e.toString());
152             }
153             handler.sendEmptyMessage(MSG_FAILED);
154             
155         }
156     }
157     
158     /**
159      * 上传图片到服务器
160      * */
161     public void uploadImage(String name,Bitmap bitmap,String path, long imageId,CallBackImage callresult){
162         this.callBackImage = callresult;
163         UploadImageThread upload = new UploadImageThread(name, bitmap, path, imageId);
164         new Thread(upload).start();
165     }
166     
167     class UploadImageThread implements Runnable{
168         String end ="\r\n";
169         String twoHyphens ="--";
170         String boundary ="*****";
171         String name = null;
172         Bitmap bitmap = null;
173         String path = null;
174         long imageId = 0;
175         public UploadImageThread(String name,Bitmap bitmap,String path, long imageId) {
176             this.name = name;
177             this.bitmap = bitmap;
178             this.path = path;
179             this.imageId = imageId;
180         }
181         @Override
182         public void run() {
183             try
184             {
185               URL url =new URL(path);
186               HttpURLConnection con=(HttpURLConnection)url.openConnection();
187               /* 允许Input、Output,不使用Cache */
188               con.setDoInput(true);
189               con.setDoOutput(true);
190               con.setUseCaches(false);
191               /* 设置传送的method=POST */
192               con.setRequestMethod("POST");
193               /* setRequestProperty */
194               con.setRequestProperty("Connection", "Keep-Alive");
195               con.setRequestProperty("Charset", "UTF-8");
196               con.setRequestProperty("Content-Type",
197                                  "multipart/form-data;boundary="+boundary);
198               
199 //              long file1 = time;
200               /* 设置DataOutputStream */
201               DataOutputStream ds =
202                 new DataOutputStream(con.getOutputStream());
203               ds.writeBytes(twoHyphens + boundary + end);
204               ds.writeBytes("Content-Disposition: form-data; "+
205                             "name=\""+imageId+"\";filename=\""+name +"\""+ end);
206               ds.writeBytes(end);  
207               /* 取得文件的FileInputStream */
208 //              FileInputStream fStream =new FileInputStream(uploadFile);
209               //bitmap  转 流
210               ByteArrayOutputStream bos = new ByteArrayOutputStream();
211               bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
212               InputStream sbs = new ByteArrayInputStream(bos.toByteArray());
213               /* 设置每次写入1024bytes */
214               int bufferSize =1024;
215               byte[] buffer =new byte[bufferSize];
216               int length =-1;
217               Log.i("msg", "PIC_UPLOAD_SUCCESS0");
218               /* 从文件读取数据至缓冲区 */
219               while((length = sbs.read(buffer)) !=-1){
220                 /* 将资料写入DataOutputStream中 */
221                 ds.write(buffer, 0, length);
222               }
223               Log.i("msg", "PIC_UPLOAD_SUCCESS1");
224               ds.writeBytes(end);
225               ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
226               /* close streams */
227               sbs.close();
228               ds.flush();
229               /* 取得Response内容 */
230               InputStream is = con.getInputStream();
231               int ch;
232               StringBuffer b =new StringBuffer();
233               while( ( ch = is.read() ) !=-1 ){
234                 b.append( (char)ch );
235               }
236               /* 将Response显示于Dialog */
237               Log.i("msg", "PIC_UPLOAD_SUCCESS2");
238               Message msg = new Message();
239               msg.what = PIC_UPLOAD_SUCCESSED;
240               String o = new String(b.toString().getBytes(), "UTF-8");
241               msg.obj = o;
242               handler.sendMessage(msg);
243               /* 关闭DataOutputStream */
244               ds.close();
245             }
246             catch(Exception e)
247             {
248                 handler.sendEmptyMessage(PIC_UPLOAD_FAILED);
249             }finally{
250                 
251             }
252             
253         }
254         
255     }
256 
257 }

 

posted on 2015-11-05 17:10  敬的男人  阅读(153)  评论(0)    收藏  举报