本文主要是介绍android中通过Http访问图片工具类的实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
网络上获取图片信息的工具类的实现: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);}@Overridepublic 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;}
}
这篇关于android中通过Http访问图片工具类的实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!