package com.zwhy.touyuan.http; import android.os.Handler; import android.os.Message; import com.zwhy.touyuan.utils.LogUtil; import com.zwhy.touyuan.utils.UIUtils; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.Map; import java.util.UUID; /** * 作者:Administrator on 2015/12/28 09:23 */ public class FileUpload { /** * 使用HttpURLConnection通过POST方式提交请求,并上传文件。 * * @param actionUrl 访问的url * @param textParams 文本类型的POST参数(key:value) * @return 服务器返回的数据,出现异常时返回 null */ public static String postWithFiles(String actionUrl, Map<String, Object> textParams,Map<String,String> filemap,Handler handler) { try { final String BOUNDARY = UUID.randomUUID().toString(); final String PREFIX = "--"; final String LINE_END = "\r\n"; final String MULTIPART_FROM_DATA = "multipart/form-data"; final String CHARSET = "UTF-8"; URL uri = new URL(actionUrl); HttpURLConnection conn = (HttpURLConnection) uri.openConnection(); //缓存大小 conn.setChunkedStreamingMode(1024 * 64); //超时 conn.setReadTimeout(5 * 1000); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Charset", "UTF-8"); conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY); // 拼接文本类型的参数 StringBuilder textSb = new StringBuilder(); if (textParams != null) { for (Map.Entry<String, Object> entry : textParams.entrySet()) { textSb.append(PREFIX).append(BOUNDARY).append(LINE_END); textSb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINE_END); textSb.append("Content-Type: text/plain; charset=" + CHARSET + LINE_END); textSb.append("Content-Transfer-Encoding: 8bit" + LINE_END); textSb.append(LINE_END); textSb.append(entry.getValue()); textSb.append(LINE_END); } LogUtil.i("-------------", "参数"); } DataOutputStream outStream = new DataOutputStream(conn.getOutputStream()); outStream.write(textSb.toString().getBytes()); //参数POST方式 //outStream.write("userId=1&cityId=26".getBytes()); // 发送文件数据 if (filemap != null) { for (Map.Entry<String, String> entry : filemap.entrySet()) { StringBuilder fileSb = new StringBuilder(); fileSb.append(PREFIX).append(BOUNDARY).append(LINE_END); fileSb.append("Content-Disposition: form-data; name=\""+entry.getKey()+"\"; filename=\"" + entry.getValue().substring(entry.getValue().lastIndexOf("/") + 1) + "\"" + LINE_END); fileSb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END); fileSb.append(LINE_END); outStream.write(fileSb.toString().getBytes()); InputStream is = new FileInputStream(entry.getValue()); byte[] buffer = new byte[1024 * 8]; int len; while ((len = is.read(buffer)) != -1) { outStream.write(buffer, 0, len); } is.close(); outStream.write(LINE_END.getBytes()); } LogUtil.i("-------------", "参数" ); } // 请求结束标志 outStream.write((PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes()); outStream.flush(); // 得到响应码 int responseCode = conn.getResponseCode(); LogUtil.i("-------------", "响应码" + responseCode); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), CHARSET)); StringBuilder resultSb = null; String line; if (responseCode == 200) { resultSb = new StringBuilder(); while ((line = br.readLine()) != null) { resultSb.append(line).append("\n"); } }else { UIUtils.showToast(UIUtils.getContext(),"网络超时"); } br.close(); outStream.close(); conn.disconnect(); LogUtil.i("-------------", "返回数据" + resultSb.toString()); Message msg = Message.obtain(); msg.obj = resultSb.toString(); handler.sendMessage(msg); return resultSb == null ? null : resultSb.toString(); } catch (IOException e) { e.printStackTrace(); } return null; } }