public synchronized String fileUpload(String url, File file) { String result = ""; OutputStream out = null; BufferedReader in = null; HttpURLConnection conn = null; final String newLine = "\r\n"; final String prefix = "--"; String BOUNDARY = "-------7da2e536604c8"; try { trustAllHosts(); URL realUrl = new URL(url); // 通过请求地址判断请求类型(http或者是https) if (realUrl.getProtocol().toLowerCase().equals("https")) { HttpsURLConnection https = (HttpsURLConnection) realUrl.openConnection(); https.setHostnameVerifier(DO_NOT_VERIFY); conn = https; } else { conn = (HttpURLConnection) realUrl.openConnection(); } // 设置通用的请求属性 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;charset=UTF-8; boundary=" + BOUNDARY); // 获取URLConnection对象对应的输出流 out = new DataOutputStream(conn.getOutputStream()); StringBuilder sb1 = new StringBuilder(); sb1.append(prefix); sb1.append(BOUNDARY); sb1.append(newLine); sb1.append("Content-Disposition:form-data;name=\"file\";filename=\"" + file.getName() + "\"" + newLine); sb1.append("Content-Type:application/octet-stream"); sb1.append(newLine); sb1.append(newLine); out.write(sb1.toString().getBytes("UTF-8")); DataInputStream input = new DataInputStream(new FileInputStream(file)); byte[] bufferOut = new byte[1024]; int bytes = 0; while ((bytes = input.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } out.write(newLine.getBytes()); input.close(); byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes(); // 写上结尾标识 out.write(end_data); // 错误方式,这种方式容易出现乱码 // PrintWriter out = new PrintWriter(connection.getOutputStream()); /*out.print(a);*/ // flush输出流的缓冲 out.flush(); int code = conn.getResponseCode(); LOG.info("url:{} , httpcode:{}", url, code); if (code == HttpURLConnection.HTTP_OK) { // 若响应码以2开头则读取响应头总的返回信息 // 定义BufferedReader输入流来读取URL的响应 if (StringUtils.isNotBlank(result)) { result = ""; } in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = in.readLine()) != null) { result += line; } } } catch (Exception e) { e.printStackTrace(); } finally {// 使用finally块来关闭输出流、输入流 try { if (out != null) { out.close(); } if (in != null) { in.close(); } if (conn != null) { conn.disconnect(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; }
HttpsURLConnection 文件上传
最新推荐文章于 2023-10-31 12:41:34 发布