您的位置:首页 > 理论基础 > 计算机网络

Android Http请求网络模拟超时

2014-01-08 16:32 357 查看


http://zhang247124629.iteye.com/blog/1490102
在Android平台上,Http请求网络有可以设置连接超时的API(conn.setConnectTimeout),在J2ME平台上就没有该API了。于是小阿哥今天小模拟一下。闲话不说了。上代码。

Java代码


package com.aisidi.age.handler;



import java.io.ByteArrayOutputStream;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.URL;



import android.graphics.Bitmap;

import android.graphics.BitmapFactory;





/**

*

* @author 小阿哥

* @date 2012-04-19

*

* */

public class Http {



private static Http http;



private HttpURLConnection conn;//连接。

private boolean isResponse;//是否有响应。。

private boolean isConnecting;//是否正在连接中。

private int connectTimeout;//连接超时时间。



private Http() {



}



public static Http getInstance() {

if (http == null) {

http = new Http();

}

return http;

}



/**

* 根据URL获得数据。字节数组。

* */

public byte[] getContentFromUrl(final String Url) {

if(this.connectTimeout!=0)

{

this.startTimer();

}



byte contentArray[] = null;

isResponse = false;

isConnecting = true;

try {

URL httpUrl = new URL(Url);

conn = (HttpURLConnection) httpUrl

.openConnection();

int responseCode = conn.getResponseCode();

if (responseCode == HttpURLConnection.HTTP_OK) {

contentArray = getByteArrayFromStream(conn.getInputStream());

}

httpUrl=null;

} catch (Exception e) {

Debug.println("getContentFromUrl Ex:" + e.toString());

} finally {

if (conn != null) {

conn.disconnect();

}

}

if (contentArray != null) {

this.isResponse = true;

}

isConnecting = false;

return contentArray;

}



/**

* 根据URL获得相应图片。

* */

public Bitmap getBitmapFromUrl(String url)

{

Bitmap bit=null;

byte file[]=getContentFromUrl(url);

if(file!=null)

{

bit=BitmapFactory.decodeByteArray(file, 0,file.length);

}

return bit;

}



/**

* 设置连接超时。

* */

public void setConnectTimeout(final int connectTimeout)

{

this.connectTimeout=connectTimeout;

}



/**

* 启动计时器线程.

* */

private void startTimer()

{

Runnable runnable=new Runnable() {

boolean isRun=true;

long startTime=System.currentTimeMillis();

long enableTime;

@Override

public void run() {

// TODO Auto-generated method stub

System.out.println("计时器线程 run start..isRun:"+isRun);

while(isRun)

{

enableTime=System.currentTimeMillis()-startTime;

if(isResponse||enableTime>=Http.this.connectTimeout)

{

System.out.println("计时器线程result str:"+(isResponse?("已经下载完毕了"):("时间延迟太长了强制关闭")));

isRun=false;

closeCurrentConnection();

break;

}



try{

Thread.sleep(50);

}catch (Exception e) {

System.out.println("计时器线程 sleep ex:"+e.toString());

}

}

System.out.println("计时器线程run..end time:"+enableTime);

}

};



new Thread(runnable).start();

}



/**

* 判断当前连接是否正在连接中。。。。

* */

public boolean isConnecting() {

return isConnecting;

}



/**

* 关闭当前连接。

* */

public void closeCurrentConnection() {

if (conn != null) {

conn.disconnect();

conn = null;

}

isResponse = false;

isConnecting = false;

}



private byte[] getByteArrayFromStream(InputStream inputStream) {

byte result[] = null;

try {

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

byte buf[] = new byte[1024];

int len;

while ((len = inputStream.read(buf)) != -1) {

outputStream.write(buf, 0, len);

}

outputStream.flush();

result = outputStream.toByteArray();

outputStream.close();

outputStream = null;

inputStream.close();

} catch (Exception e) {

Debug.println("getStreamByteArray().EX:" + e.toString());

}

return result;

}

}

以上代码是模拟连接超时的主要逻辑代码。亲,上面的代码还有注释哟,专门为你写的。是不是很体贴啊。

Java代码


package com.aisidi.age.handler;





import android.content.Context;

import android.graphics.Bitmap;

import android.graphics.Canvas;

import android.graphics.Color;

import android.view.KeyEvent;

import android.view.View;

import android.widget.Toast;



/**

*

* @author 小阿哥

* @date 2012-04-19

*

* */

public class MyView extends View implements Runnable{



private static final int CONNECTION_TIMEOUT = 800;

private static final String URL_DOWN_LOAD="http://ww3.sinaimg.cn/large/979d743fjw1ds3igt92dkj.jpg";

private static final String CONNECTING_TOAST="正在连网中。请稍候在试。。";



private Bitmap bitDownLoad;



public MyView(Context context) {

super(context);

// TODO Auto-generated constructor stub

new Thread(this).start();

this.setFocusable(true);

this.setFocusableInTouchMode(true);

}



@Override

protected void onDraw(Canvas canvas) {

// TODO Auto-generated method stub

super.onDraw(canvas);

canvas.drawColor(Color.BLACK);

if(bitDownLoad!=null)

{

canvas.drawBitmap(bitDownLoad, 0,0,null);

}

}



@Override

public boolean onKeyDown(int keyCode, KeyEvent event) {

// TODO Auto-generated method stub

if(keyCode==KeyEvent.KEYCODE_BACK)//当按返回键时,请求网络下载图片。

{

if(Http.getInstance().isConnecting())

{

Toast.makeText(this.getContext(), CONNECTING_TOAST, Toast.LENGTH_LONG).show();

}

else

{

requestBitmap(URL_DOWN_LOAD);

}

return true;

}

return super.onKeyDown(keyCode, event);

}



//请求网络下载图片

public void requestBitmap(final String url)

{

new Thread(new Runnable() {

@Override

public void run() {

// TODO Auto-generated method stub

if(bitDownLoad!=null)

{

bitDownLoad=null;

}

long startTime=System.currentTimeMillis();

Http.getInstance().setConnectTimeout(CONNECTION_TIMEOUT);

bitDownLoad=Http.getInstance().getBitmapFromUrl(url);

System.out.println("请求图片线程run end time:"+(System.currentTimeMillis()-startTime)+"__"+((bitDownLoad!=null)?("有数据了"):("!!没有数据")));

}

}).start();

}





@Override

public void run() {

// TODO Auto-generated method stub

while(true)

{

this.postInvalidate();

try{

Thread.sleep(50);

}catch(Exception ex)

{

System.out.println("Thread.sleep.EX:"+ex.toString());

}

}

}

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: