网络上获取图片信息的工具类的实现:
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;
}
}