/** * 上传文件 *  * @param uploadUrl *            上传地址 * @param param *            参数 * @param filepath *            文件路径 * @return 结果 */public static String upload(String uploadUrl, HashMap<String, String> param, String fieldName, String filepath) {StringBuilder result = null;try {String boundary = "---------------------------esa000000000001";URL url = new URL(uploadUrl);HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setDoOutput(true);connection.setDoInput(true);connection.setUseCaches(false);connection.setConnectTimeout(1000 * 20);connection.setReadTimeout(1000 * 20);connection.setRequestMethod("POST");connection.setRequestProperty("Connection", "Keep-Alive");connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);connection.setRequestProperty("Charsert", "UTF-8");File file = new File(filepath);StringBuilder sbf = new StringBuilder();sbf.append("--" + boundary + "\r\n");sbf.append("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + file.getName() + "\"\r\n");sbf.append("Content-Type: application/octet-stream" + "\r\n\r\n");byte[] fz = sbf.toString().getBytes();StringBuilder sb = new StringBuilder();sb.append("\r\n\r\n");Iterator<String> iterator = param.keySet().iterator();while (iterator.hasNext()) {String key = iterator.next();String value = param.get(key);sb.append("--" + boundary + "\r\n");sb.append("Content-Disposition: form-data; name=\"" + key + "\"\r\n");sb.append("\r\n");sb.append(value + "\r\n");}byte[] before = sb.toString().getBytes();byte[] after = ("\r\n--" + boundary + "--\r\n").getBytes();connection.setRequestProperty("content-length", (before.length + fz.length + file.length() + after.length) + "");DataOutputStream dos = new DataOutputStream(connection.getOutputStream());dos.write(fz);FileInputStream fis = new FileInputStream(file);byte[] buffer = new byte[1024 * 10];int len;while ((len = fis.read(buffer)) != -1) {dos.write(buffer, 0, len);}dos.write(before);dos.write(after);dos.flush();int code = connection.getResponseCode();InputStream stream = connection.getInputStream();byte[] b = new byte[1024 * 10];int l;result = new StringBuilder();while ((l = stream.read(b)) != -1) {result.append(new String(b, 0, l, "utf-8"));}fis.close();dos.close();stream.close();} catch (MalformedURLException e) {} catch (ProtocolException e) {} catch (IOException e) {} finally {}if (result == null) {return null;} else {return result.toString();}}

更多相关文章

  1. android工程没有gen路径
  2. Android那些疑惑(2)-LayoutInflater中inflate方法参数的意义
  3. Android如何获取asset目录下所有文件的路径
  4. android 跳转并传递参数
  5. android 蓝牙ble app开发(二) -- 关键概念,连接参数,连接请求
  6. Android activity 参数传递

随机推荐

  1. android TextView 设置部分文本 边框和样
  2. Android获取手机型号,系统版本,App版本号
  3. Android屏幕休眠和唤醒
  4. Android(安卓)SpannableString 自定义圆
  5. android uuid
  6. Android之TabHost的几种使用方法
  7. android 获取root修改系统时间
  8. android:随记
  9. android 如何判断程序是否在前台运行
  10. android开发常用问题总结