HttpClien实现使用post方式模拟表单上传大文件和字符参数

来源:互联网 发布:什么软件学英语最好 编辑:程序博客网 时间:2024/04/29 23:29

前提:自行准备好httpmime.jar

/** * HttpClien实现模拟表单post提交文件数据和字符参数,并支持大文件上传 * @author dance * */public class HttpClientUploadManager {public interface HttpClientUploadResponse {int SUCCESS = 1;int FAIL = 0;}/** * 该方式是支持大文件上传的,如果用HttpURLConnection一般只能上传5M以内的,再大就OOM了 * @param handler activity宿主handler * @param url  * @param filepath 文件路径 * @param fileKey 文件对应的key * @param mapParams 字符参数的key和值封装好传入 */public static void upload(Handler handler, String url, String filepath,String fileKey, HashMap<String, String> mapParams) {HttpClient client = new DefaultHttpClient();HttpPost httpPost = new HttpPost(url);client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION,HttpVersion.HTTP_1_1);client.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "utf-8");try {MultipartEntity entity = new MultipartEntity();// 文件参数部分File file = new File(filepath);ContentBody fileBody = new FileBody(file); // fileentity.addPart(fileKey, fileBody);// 字符参数部分Set<String> set = mapParams.keySet();for (String key : set) {entity.addPart(key, new StringBody(mapParams.get(key)));}httpPost.setEntity(entity);HttpResponse response = client.execute(httpPost);Message message = handler.obtainMessage();if (response.getStatusLine().getStatusCode() == 200) { // 成功//获取服务器返回值HttpEntity responseEntity = response.getEntity();InputStream input = responseEntity.getContent();StringBuilder sb = new StringBuilder();int s;while ((s = input.read()) != -1) {sb.append((char) s);}String result = sb.toString();LogUtil.i("HttpClientUploadManager", "http client upload result: " + result);message.what = HttpClientUploadResponse.SUCCESS;message.obj = result;//将数据返回给activity}else {message.what = HttpClientUploadResponse.FAIL;}handler.sendMessage(message);} catch (Exception e) {Message message = handler.obtainMessage();message.what = HttpClientUploadResponse.FAIL;handler.sendMessage(message);}}}


0 0
原创粉丝点击