HTML5技术

如何独立开发一个网络请求框架 - 指尖下的幽灵(6)

字号+ 作者:H5之家 来源:博客园 2016-08-15 11:00 我要评论( )

* LghHttp 基础数据类 3 * 作为 handler 传递的数据种子,只在成功时传递 HttpDataBean implements Serializable{ String response; 8 private LghHttpSingleListener listeners; setResponse(String response){ 11

* LghHttp 基础数据类 3 * 作为 handler 传递的数据种子,只在成功时传递 HttpDataBean implements Serializable{ String response; 8 private LghHttpSingleListener listeners; setResponse(String response){ 11 this.response = response; 12 } setListeners(LghHttpSingleListener listeners){ 15 this.listeners = listeners; 16 } String getResponse(){ .response; 20 } LghHttpSingleListener getListeners(){ .listeners; 24 } 25 }

View Code

    3)请求核心部分

  7,拓展,加入视频上传部分。

 

完整代码:

  上面嵌套讲解拆分了,这里提供完整的。

 

1 package com.lghsaleimage; android.graphics.Bitmap; 4 import android.os.Handler; 5 import android.os.Message; 6 import android.util.Log; java.io.BufferedReader; 9 import java.io.ByteArrayInputStream; 10 import java.io.ByteArrayOutputStream; 11 import java.io.DataOutputStream; 12 import java.io.IOException; 13 import java.io.InputStream; 14 import java.io.InputStreamReader; 15 import java.io.OutputStream; 16 import java.io.Serializable; 17 import java.io.UnsupportedEncodingException; 18 import java.net.HttpURLConnection; 19 import java.net.MalformedURLException; 20 import java.net.ProtocolException; 21 import java.net.SocketTimeoutException; 22 import java.net.URL; 23 import java.util.concurrent.Executors; 24 import java.util.concurrent.ThreadPoolExecutor; * Created by 林冠宏(指尖下的幽灵) on 2016/8/11. 28 * ; 30 * 31 * Name : http 工具类 32 * 33 * 前言: 34 * 希望大家能够和我一起来完善它,该类肯定有很多不足的,但总体来说,还是不错的。 35 * 36 * 下面是简介和拓展: 37 * 38 * 1, 考虑到网络请求必不可少,采用了静态内部类单例模式 39 * 40 * 2, 采用 newFixedThreadPool 线程池来管理并发线程, 41 * 如果要替换,建议使用 newCacheThreadPool 42 * 43 * 3, 功能方面提供三种常见操作: 44 * 1)Get请求 45 * 2)Post请求 46 * 3)图片上传 47 * 4, 优点: 48 * 1) 绝对的轻量级,可以提升 APK 体积优化 49 * 2)内存管理方面可以放心 50 * 3)请求速度方法是纯系统的 HttpUrlConnection 请求, 51 * 没有过多的代码片段 52 * 53 * 5,可以进一步解耦拆分类,分为: 54 * 1)公共部分 55 * 2)数据部分 56 * 3)请求核心部分 57 * 58 * 6, 加入视频上传部分 59 * LghHttp { String TAG = "zzzzz"; Success = 0x10; UrlFailed = 0x11; TimeOut = 0x12; ProtocolFailed = 0x13; EncodingFailed = 0x14; IOFailed = 0x15; IsOpenCompress = CompressLimit = 500; ThreadPoolExecutor threadPool; 77 private Handler handler; * 全局回调接口 GloblelghHttpListeners 80 * 注意: 81 * 个人建议,如果请求页面多的,那就不要使用全局接口。尽量采用singleInterface 82 * 否则,你需要在用户层页面的每次onResume重新设置 LghHttpGlobleListener GloblelghHttpListeners; LghHttp getInstance(){ 87 return LghHttpStatic.singleLghHttp; 88 } LghHttpStatic{ LghHttp singleLghHttp = new LghHttp(); 92 } destroy(){ 96 if(threadPool!=null){ 97 if(!threadPool.isShutdown()){ 98 threadPool.shutdown(); 99 threadPool = null; 100 } 101 } 102 if(handler!=null){ 103 handler.removeCallbacksAndMessages(null); 104 handler = null; 105 } 106 if(GloblelghHttpListeners!=null){ 107 GloblelghHttpListeners = null; 108 } 109 LghHttpStatic.singleLghHttp = null; 110 } setGloblelghHttpListeners(LghHttpGlobleListener GloblelghHttpListeners){ 113 this.GloblelghHttpListeners = GloblelghHttpListeners; 114 } * LghHttp 基础数据类 118 * 作为 handler 传递的数据种子,只在成功时传递 HttpDataBean implements Serializable{ String response; 123 private LghHttpSingleListener listeners; setResponse(String response){ 126 this.response = response; 127 } setListeners(LghHttpSingleListener listeners){ 130 this.listeners = listeners; 131 } String getResponse(){ .response; 135 } LghHttpSingleListener getListeners(){ .listeners; 139 } 140 } init(){ 144 this.threadPool = (ThreadPoolExecutor) Executors.newFixedThreadPool(3); 145 this.handler = new Handler(){ 146 @Override handleMessage(Message msg) { 148 super.handleMessage(msg); 149 150 HttpDataBean bean = (HttpDataBean) msg.obj; 151 LghHttpBaseListenr tempListener; tempListener = GloblelghHttpListeners; 154 }else if(bean.getListeners()!=null){ 155 tempListener = bean.getListeners(); 156 }else{ 157 return; 158 } 159 switch (msg.what){ 160 case Success: GloblelghHttpListeners.onSuccess(msg.arg1,bean.getResponse()); 163 }else{ 164 bean.getListeners().onSuccess(bean.getResponse()); 165 } 166 break; 167 case UrlFailed: 168 tempListener.onFailed(UrlFailed); 169 break; 170 case TimeOut: 171 tempListener.onFailed(TimeOut); 172 break; 173 case ProtocolFailed: 174 tempListener.onFailed(ProtocolFailed); 175 break; 176 case EncodingFailed: 177 tempListener.onFailed(EncodingFailed); 178 break; 179 case IOFailed: 180 tempListener.onFailed(IOFailed); 181 break; 182 default: ; 185 } 186 } 187 }; 188 } sendMessage(int what,int code,Object object){ 192 Message msg = new Message(); 193 msg.what = what; 194 msg.arg1 = code; 195 msg.obj = object; 196 handler.sendMessage(msg); 197 } sendMessage(int what,Object object){ 200 sendMessage(what, -1, object); 201 } * requestCode 请求标识符,方便区分 doGet(final String url){ 209 doGet(-1, url, null); 210 } doGet(final int requestCode,final String url){ 213 doGet(requestCode, url, null); 214 } doGet( requestCode, 218 final String url, 219 final LghHttpSingleListener lghHttpListeners) 220 { 221 Runnable runnable = new Runnable() { 222 @Override run() { 224 get(requestCode, url, lghHttpListeners); 225 } 226 }; 227 if(threadPool != null){ 228 threadPool.execute(runnable); 229 }else{ 230 Log.d(TAG,"do get threadPool is null"); 231 } 232 } get(int requestCode,String url,LghHttpSingleListener lghHttpListener){ 235 try { 236 HttpURLConnection httpURLConnection = getHttpUrlConnection(url,"GET"); 237 httpURLConnection.setUseCaches(false); 238 sendMessage(Success,requestCode, commonGetResult(httpURLConnection,lghHttpListener)); 239 } catch (MalformedURLException e) { 240 dealWithException(e,lghHttpListener); 241 } catch (IOException e) { 242 dealWithException(e,lghHttpListener); 243 } 244 } doPost(String url){ 248 doPost(-1, url); 249 } doPost(int requestCode,String url){ 252 doPost(requestCode, url, null, null); 253 } doPost(int requestCode,String url,LghHttpSingleListener listener){ 256 doPost(requestCode, url, null, null,listener); 257 } doPost(int requestCode,String url,String[] keys,String[] values){ 260 doPost(requestCode, url, keys, values, null); 261 } doPost( requestCode, 265 final String url, 266 final String[] keys, 267 final String[] values, 268 final LghHttpSingleListener listener 269 ){ 270 Runnable runnable = new Runnable() { 271 @Override run() { 273 post(requestCode, url,keys,values, listener); 274 } 275 }; 276 if(threadPool != null){ 277 threadPool.execute(runnable); 278 }else{ 279 Log.d(TAG,"do post threadPool is null"); 280 } 281 } post( 285 int requestCode, 286 String url, 287 String[] keys, 288 String[] values, 289 LghHttpSingleListener listener 290 ){ 291 if(url==null){ 292 return; 293 } 294 try{ 295 HttpURLConnection httpURLConnection = getHttpUrlConnection(url,"POST"); httpURLConnection.setUseCaches(false); (keys!=null && values!=null){ 300 OutputStream outputStream = httpURLConnection.getOutputStream(); 301 commonCombinePostText(keys,values,outputStream); 302 outputStream.flush(); 303 outputStream.close(); 304 } 305 sendMessage(Success,requestCode, commonGetResult(httpURLConnection,listener)); 306 }catch (MalformedURLException e){ 307 dealWithException(e,listener); 308 } catch (SocketTimeoutException e){ 309 dealWithException(e,listener); 310 } catch (ProtocolException e) { 311 dealWithException(e,listener); 312 } catch (UnsupportedEncodingException e) { 313 dealWithException(e,listener); 314 } catch (IOException e) { 315 dealWithException(e,listener); 316 } 317 } doUpLoadPic( 321 String url, 322 String picName, 323 String streamName, 324 Bitmap bit 325 ){ 326 doUpLoadPic(-1, url, null, null, picName, streamName, bit, null); 327 } doUpLoadPic( 330 int requestCode, 331 String url, 332 String picName, 333 String streamName, 334 Bitmap bit 335 ){ 336 doUpLoadPic(requestCode, url, null, null, picName, streamName, bit, null); 337 } doUpLoadPic( 340 int requestCode, 341 String url, 342 String picName, 343 String streamName, 344 Bitmap bit, 345 LghHttpSingleListener listener 346 ){ 347 doUpLoadPic(requestCode, url, null, null, picName, streamName, bit, listener); 348 } doUpLoadPic( 351 int requestCode, 352 String url, 353 String[] keys, 354 String[] values, 355 String picName, 356 String streamName, 357 Bitmap bit 358 ){ 359 doUpLoadPic(requestCode, url, keys, values, picName, streamName, bit, null); 360 } doUpLoadPic( requestCode, 364 final String url, 365 final String[] keys, 366 final String[] values, 367 final String picName, 368 final String streamName, 369 final Bitmap bit, 370 final LghHttpSingleListener listener 371 ){ 372 Runnable runnable = new Runnable() { 373 @Override run() { 375 UpLoadPic(requestCode, url, keys, values, picName, streamName, bit, listener); 376 } 377 }; 378 if(threadPool != null){ 379 threadPool.execute(runnable); 380 }else{ 381 Log.d(TAG,"do post threadPool is null"); 382 } 383 } * 此函数用来上传图片 387 * post 的 两种数据包格式: 388 * 1,application/x-www-form-urlencoded;用来上传文字 389 * 2,multipart/form-data; 二进制传输,除了文字之外,还可以用来传输 文件,例如图片! 390 * 3,multipart/form-data; 必须要带有分隔符 boundary 391 * 4,在http post请求的结尾,需要有一个分界线,但是是前后都有--的:--分隔符-- 392 * 参数: 393 * url 394 * picName 图片的名称 395 * streamName 流体值的名称 396 * 例如采用 php 接收,那么在服务器获取图片名称的写法是:$_FILES['streamName']['picName'] UpLoadPic( 399 int requestCode, 400 String url, 401 String[] keys, 402 String[] values, 403 String picName, 404 String streamName, 405 Bitmap bit, 406 LghHttpSingleListener listener 407 ){ String boundary = "******"; { 411 HttpURLConnection httpURLConnection = getHttpUrlConnection(url,"POST"); 412 httpURLConnection.setUseCaches(false); 413 httpURLConnection.setDoOutput(true); httpURLConnection.setRequestProperty("Connection","Keep-Alive"); 417 httpURLConnection.setRequestProperty("Content-Type","multipart/form-data;boundary="+boundary); DataOutputStream body = new DataOutputStream(httpURLConnection.getOutputStream()); body.writeBytes(twoHyphens+boundary+"\r\n"); body.writeBytes( 423 "Content-Disposition:form-data;" + 424 "name=\"" + streamName + "\";" + 425 "filename=\"" + picName + "\"" + "\r\n" 426 ); body.writeBytes("\r\n"); 429 if(keys!=null && values!=null){ 430 body.writeBytes(twoHyphens+boundary+"\r\n"); 431 body.writeBytes("Content-Disposition:form-data;"); 432 commonCombinePostText(keys,values,body); 433 body.writeBytes("\r\n"); 434 } compress = 100; 438 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 439 bit.compress(Bitmap.CompressFormat.JPEG, compress, baos); 440 if(IsOpenCompress){ 441 while (baos.toByteArray().length / 1024 > CompressLimit) { 442 baos.reset(); 443 compress -= 10; 444 if(compress==0){ 445 bit.compress(Bitmap.CompressFormat.JPEG, compress, baos); 446 break; 447 } 448 bit.compress(Bitmap.CompressFormat.JPEG, compress, baos); 449 } 450 } InputStream picStream = new ByteArrayInputStream(baos.toByteArray()); [10*1024]; 454 int count; 455 while((count = picStream.read(buffer))!=-1){ 456 body.write(buffer,0,count); 457 } 458 picStream.close(); 459 body.writeBytes("\r\n"); 460 body.writeBytes(twoHyphens + boundary + twoHyphens +"\r\n"); 461 body.flush(); sendMessage(Success,requestCode,commonGetResult(httpURLConnection,listener)); 464 body.close(); 465 }catch (MalformedURLException e){ 466 dealWithException(e,listener); 467 } catch (SocketTimeoutException e){ 468 dealWithException(e,listener); 469 } catch (ProtocolException e) { 470 dealWithException(e,listener); 471 } catch (UnsupportedEncodingException e) { 472 dealWithException(e,listener); 473 } catch (IOException e) { 474 dealWithException(e,listener); 475 } 476 } dealWithException( 480 Exception e, 481 LghHttpSingleListener lghHttpListeners) 482 { 483 HttpDataBean bean = new HttpDataBean(); 484 bean.setListeners(lghHttpListeners); 485 if(e instanceof MalformedURLException){ 486 Log.d(TAG, "链接格式有问题 "+e.toString()); 487 sendMessage(UrlFailed,bean); 488 }else if(e instanceof SocketTimeoutException){ 489 Log.d(TAG, "连接超时 "+e.toString()); 490 sendMessage(TimeOut,bean); 491 }else if(e instanceof ProtocolException){ 492 Log.d(TAG, "协议异常,注意不要多次连接 " + e.toString()); 493 sendMessage(ProtocolFailed, bean); 494 }else if(e instanceof UnsupportedEncodingException){ 495 Log.d(TAG, "编码类型异常 " + e.toString()); 496 sendMessage(EncodingFailed, bean); 497 }else if(e instanceof IOException){ 498 Log.d(TAG, "io 异常 " + e.toString()); 499 sendMessage(IOFailed,bean); 500 } 501 } HttpURLConnection getHttpUrlConnection 505 (String url,String requestWay) throws IOException { 506 Log.d(TAG,"url is "+url); 507 URL mRrl = new URL(url); 508 HttpURLConnection httpURLConnection = (HttpURLConnection) mRrl.openConnection(); 509 httpURLConnection.setRequestMethod(requestWay); 510 httpURLConnection.setRequestProperty("Charset", "UTF-8"); 511 httpURLConnection.setConnectTimeout(5 * 1000); 512 return httpURLConnection; 513 } HttpDataBean commonGetResult( 517 HttpURLConnection httpURLConnection, 518 LghHttpSingleListener listener 519 ) throws IOException { 520 if(httpURLConnection==null){ ; 522 } 523 BufferedReader br = new BufferedReader 524 ( 525 new InputStreamReader(httpURLConnection.getInputStream(),"UTF-8"), 526 8*1024 527 ); 528 StringBuffer resultBuffer = new StringBuffer(""); 529 String line; 530 while ((line = br.readLine())!=null){ 531 resultBuffer.append(line); 532 } 533 HttpDataBean bean = new HttpDataBean(); 534 bean.setResponse(resultBuffer.toString()); 535 bean.setListeners(listener); 536 br.close(); 537 return bean; 538 } OutputStream commonCombinePostText( 542 String[] keys, 543 String[] values, 544 OutputStream outputStream) throws IOException 545 { 546 StringBuffer requestStr = new StringBuffer(); 547 int keysLength = keys.length; 548 for(int i=0;i<keysLength;i++){ 549 requestStr.append(keys[i]+"="+values[i]+"&"); 550 } 551 outputStream.write(requestStr.toString().getBytes()); 552 return outputStream; 553 } LghHttpBaseListenr{ 557 void onFailed(int type); 558 // void onUrlFailed(); 559 // void onTimeOut(); 560 // void onProtocolFailed(); 561 // void onEncodingFailed(); } LghHttpGlobleListener extends LghHttpBaseListenr{ 567 void onSuccess(int requestCode,String response); 568 } LghHttpSingleListener extends LghHttpBaseListenr{ 572 void onSuccess(String response); 573 } 574 575 }

 

 

用法例子

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
  • 用TypeScript开发Vue——如何通过vue实例化对象访问实际ViewModel对象 - 小小沧海

    用TypeScript开发Vue——如何通过vue实例化对象访问实际ViewModel对

    2016-08-12 10:00

  • 拥抱.NET Core,如何开发一个跨平台类库 (1) - KAnts

    拥抱.NET Core,如何开发一个跨平台类库 (1) - KAnts

    2016-08-08 14:00

  • webkit webApp 开发技术要点总结 - -小克

    webkit webApp 开发技术要点总结 - -小克

    2016-07-29 17:00

  • ckplayer 如何在PC上完美支持 m3u8播放 - 冒雨ing

    ckplayer 如何在PC上完美支持 m3u8播放 - 冒雨ing

    2016-07-27 11:00

网友点评