public static String doFilePost(String urlstr, Map<String, String> map,Map<String, File> files) throws Exception { String BOUNDARY = "-------------------------acebdf13572468"; // 定义数据分隔线 String LINE_END = "\r\n"; URL url = new URL(urlstr); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 发送POST请求必须设置如下两行 connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); connection.setRequestMethod("POST"); connection.setRequestProperty("Accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Android WYJ"); connection.setRequestProperty("Charsert", "UTF-8"); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); OutputStream out = new DataOutputStream(connection.getOutputStream()); byte[] end_data = ("--" + BOUNDARY + "--\r\n").getBytes();// 定义最后数据分隔线 // 文件 if (files != null && !files.isEmpty()) { for (Map.Entry<String, File> entry : files.entrySet()) { File file = entry.getValue(); String fileName = entry.getKey(); StringBuilder sb = new StringBuilder(); sb.append("--"); sb.append(BOUNDARY); sb.append("\r\n"); sb.append("Content-Disposition: form-data;name=\"" + fileName+ "\";filename=\"" + file.getName() + "\"\r\n"); sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END); byte[] data = sb.toString().getBytes(); out.write(data); DataInputStream in = new DataInputStream(new FileInputStream(file)); int bytes = 0; byte[] bufferOut = new byte[1024]; while ((bytes = in.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } out.write("\r\n".getBytes()); // 多个文件时,二个文件之间加入这个 in.close(); } } // 数据参数 if (map != null && !map.isEmpty()) { for (Map.Entry<String, String> entry : map.entrySet()) { StringBuilder sb = new StringBuilder(); sb.append("--"); sb.append(BOUNDARY); sb.append("\r\n"); sb.append("Content-Disposition: form-data; name=\""+ entry.getKey() + "\""); sb.append("\r\n"); sb.append("\r\n"); sb.append(URLEncoder.encode(entry.getValue(),"utf-8")); sb.append("\r\n"); Debug.d("map = "+sb.toString()); byte[] data = sb.toString().getBytes(); out.write(data); } } out.write(end_data); out.flush(); out.close(); int code = connection.getResponseCode(); if (code == HttpURLConnection.HTTP_OK) { InputStream inStream = connection.getInputStream(); byte[] number = read(inStream); String json = new String(number); Debug.d("result : " + json); return json; } return null; } public static byte[] read(InputStream inStream) throws IOException { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } inStream.close(); outStream.close(); return outStream.toByteArray(); }
Android上传文本携带参数
最新推荐文章于 2021-05-27 12:32:40 发布