Android 开发中的常用的上传下载接口
先定义三个接口用来处理返回的数据;
public interface IHttpPostCompleted {
void onHttpPostCompleted(String responseText) ;
}
public interface IHttpPostError {
void onHttpPostError(int statusCode );
}
public interface IExecuteException {
void onExecuteException(Exception e);
}
-------------------------辅助类-------------------
public class UriImageCache {
public static String parse(String url) {
if (url == null || url == "")
return null;
String sk = url.toLowerCase();
String name = String.format("%d.imgdata", sk.hashCode() );
return getImagePath(name);
}
}
-----------------------上传下载的常用接口-----------------
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.http.AndroidHttpClient;
import android.util.Log;
public class urlhelper {
public static boolean checkUrl(String path) {
boolean ok = false;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(path);
try {
HttpResponse response = httpclient.execute(httppost);
int code = response.getStatusLine().getStatusCode();
ok = code == HttpStatus.SC_OK;
} catch (Exception e) {
}
return ok;
}
public static void doPost(String path, IHttpPostCompleted ready,
IHttpPostError error, IExecuteException exception) {
urlhelper.doPost(path, null, ready, error, exception);
}
public static void doPost(String actionUrl, Map
IHttpPostCompleted ready, IHttpPostError error, IExecuteException exception
) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(actionUrl);
try {
if (params != null && params.isEmpty() == false) {
List
params.size());
for (Entry
if (enty.getValue() == null) ///-------------这个不能丢
continue;
nameValuePairs.add(new BasicNameValuePair(enty.getKey(),
enty.getValue()));
}
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,
"UTF-8"));
httppost.setHeader("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
}
HttpResponse response = httpclient.execute(httppost);
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
StringBuffer sb = new StringBuffer();
String sResponse = null;
while ((sResponse = reader.readLine()) != null) {
sb.append(sResponse);
}
if (ready != null) {
ready.onHttpPostCompleted(sb.toString());
}
} else {
if (error != null) {
error.onHttpPostError(code);
}
}
} catch (Exception e) {
if (exception != null) {
exception.onExecuteException(e);
}
}
}
/**
* 上传文件的接口
*
* @param actionUrl
* @param params
* @param imageFile
* @param ready
* @param error
* @param exception
*/
public static void doPost(String actionUrl, Map
String filePath, IHttpPostCompleted ready, IHttpPostError error,
IExecuteException exception
) {
File file = new File(filePath);
if (file.exists() == false) {
if (exception != null) {
exception.onExecuteException(new Exception("文件不存在"));
}
return;
}
if (file.isFile() == false) {
if (exception != null) {
exception
.onExecuteException(new FileNotFoundException(filePath));
}
return;
}
if (file.canRead() == false) {
if (exception != null) {
exception.onExecuteException(new Exception("无文件读取权限"));
}
return;
}
if (file.length() == 0L) {
if (exception != null) {
exception.onExecuteException(new Exception("不可以上传空文件"));
}
return;
}
Bitmap bitmap = null;
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFile(filePath, o2);
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(actionUrl);
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
try {
if (params != null && params.size() > 0) {
for (Map.Entry
String val = entry.getValue();
if (val == null)
continue;
entity.addPart(entry.getKey(), new StringBody(val));
}
}
entity.addPart("imagefile", new ByteArrayBody(data, file.getName()));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
StringBuffer sb = new StringBuffer();
String sResponse = reader.readLine();
while (sResponse != null) {
sb.append(sResponse);
sResponse = reader.readLine();
}
if (ready != null) {
ready.onHttpPostCompleted(sb.toString());
}
} else {
if (error != null) {
error.onHttpPostError(code);
}
}
} catch (Exception e) {
if (exception != null) {
exception.onExecuteException(e);
}
}
}
public static Bitmap downloadBitmap(String url) {
// AndroidHttpClient is not allowed to be used from the main thread
final String LogTag = "downloadBitmap";
final HttpClient client =new DefaultHttpClient(); // 可以换成 AndroidHttpClient
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode
+ " while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
inputStream = entity.getContent();
String phyicalPath = UriImageCache.parse(url);
FileOutputStream fos = new FileOutputStream(phyicalPath,
true);
DataHelper.copyStream(inputStream, fos);
// return BitmapFactory.decodeStream(inputStream);
// Bug on slow connections, fixed in future release.
return BitmapFactory.decodeFile(phyicalPath);
// return BitmapFactory.decodeStream(new
// FlushedInputStream(inputStream));
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (IOException e) {
getRequest.abort();
Log.w(LogTag, "I/O error while retrieving bitmap from " + url, e);
} catch (IllegalStateException e) {
getRequest.abort();
Log.w(LogTag, "Incorrect URL: " + url);
} catch (Exception e) {
getRequest.abort();
Log.w(LogTag,
"Error while retrieving bitmap from " + url, e);
} finally {
/* 用 AndroidHttpClient 时需要处理的数据
if ((client instanceof AndroidHttpClient)) {
((AndroidHttpClient) client).close();
}
*/
}
return null;
}
}
PS:-这些代码都是从网上,书上和自己做的项目中边学边改的,提取出来放在这里,希望对那位兄弟有用。。
更多相关文章
- Android中的文件存储练习
- android 多渠道打包,build.gradle文件配置、manifest文件配置
- android 6.0 创建文件或文件夹失败
- Java(Android)对文件全文生成MD5摘要
- Android编译系统详解 配置文件
- Android 数据存储(数据库、文件、参数)操作实例
- Android中手机文件储存路径
- android 串口通信,蓝牙通信等需要输出十六进制数据的方法
- android极简原创系列:最简单的listview数据绑定