/** * 上传文件到指定地址URL * * @param fileName 文件名 * @param inStream 输入流 * @param urlStr 上传地址 * @return */ private String uploadFile(String fileName, ByteArrayInputStream inStream, String urlStr) { try { // 换行符 final String newLine = "\r\n"; // 服务器的上传地址 URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 设置为POST情 conn.setRequestMethod("POST"); // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); // 设置请求头参数 conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundaryari0emH33oMihIU4"); conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36"); OutputStream out = new DataOutputStream(conn.getOutputStream()); // 上传文件 StringBuilder sb = new StringBuilder(); sb.append(newLine); // 文件参数 sb.append("------WebKitFormBoundaryari0emH33oMihIU4\n" + "Content-Disposition: form-data; name=\"Filedata\"; filename=\"" + fileName + "\""); sb.append("Content-Type:application/octet-stream"); // 参数头设置完以后需要两个换行,然后才是参数内容 sb.append(newLine); sb.append(newLine); // 将参数头的数据写入到输出流中 out.write(sb.toString().getBytes()); // 数据输入流,用于读取文件数据 DataInputStream in = new DataInputStream(inStream); byte[] bufferOut = new byte[2048]; int bytes = 0; // 每次读2KB数据,并且将文件数据写入到输出流中 while ((bytes = in.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } // 最后添加换行 out.write(newLine.getBytes()); in.close(); // 定义最后数据分隔线,即--加上BOUNDARY再加上--。 byte[] end_data = "------WebKitFormBoundaryari0emH33oMihIU4--".getBytes(); // 写上结尾标识 out.write(end_data); out.flush(); out.close(); // 定义BufferedReader输入流来读取URL的响应 BufferedReader reader = new BufferedReader(new InputStreamReader( conn.getInputStream(),"UTF-8")); StringBuffer buffer = new StringBuffer(); String line = null; while ((line = reader.readLine()) != null) { buffer.append(line); } return buffer.toString(); } catch (Exception e) { System.out.println("发送POST请求出现异常!" + e); e.printStackTrace(); } return ""; }
JAVA http post 上传文件
最新推荐文章于 2024-05-29 22:50:44 发布