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

android中通过Http访问图片工具类的实现

2013-12-23 21:25 531 查看
网络上获取图片信息的工具类的实现:
package com.demo.loading;

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.http.AndroidHttpClient;

public class ImageGetForHttp {

/**
* 通过URL获取bitmap对象
*
* @param url
* @param type
* @return
*/
public static Bitmap downloadBitmap(String url, String type) {
final HttpClient client = AndroidHttpClient.newInstance("Android");
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}

final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
inputStream = entity.getContent();
FilterInputStream fit = new FlushedInputStream(inputStream);
Bitmap bm = BitmapFactory.decodeStream(fit);
Bitmap bitmap = ImageRedraw.getInstance().redrawImg(bm,
type);
return bitmap;
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (IOException e) {
getRequest.abort();
e.printStackTrace();
} catch (IllegalStateException e) {
getRequest.abort();
e.printStackTrace();
} catch (Exception e) {
getRequest.abort();
e.printStackTrace();
} finally {
if ((client instanceof AndroidHttpClient)) {
((AndroidHttpClient) client).close();
}
}
return null;
}

/*
* An InputStream that skips the exact number of bytes provided, unless it
* reaches EOF.
*/
static class FlushedInputStream extends FilterInputStream {
public FlushedInputStream(InputStream inputStream) {
super(inputStream);
}

@Override
public long skip(long n) throws IOException {
long totalBytesSkipped = 0L;
while (totalBytesSkipped < n) {
long bytesSkipped = in.skip(n - totalBytesSkipped);
if (bytesSkipped == 0L) {
int b = read();
if (b < 0) {
break; // we reached EOF
} else {
bytesSkipped = 1; // we read one byte
}
}
totalBytesSkipped += bytesSkipped;
}
return totalBytesSkipped;
}
}

/**
* 通过URL获取字节数组对象
*
* @param hostURL
* @param headParams
* @return
*/
public static byte[] getStream(final String hostURL) {
HTTPRequest httpGet = new HTTPRequest();
byte[] BufferData = null;
try {
BufferData = httpGet.httpRequestByteArray(hostURL);
} catch (Exception e) {
e.printStackTrace();
}
return BufferData;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐