java发起URL的post表单请求上传视频

     /**
	 * 上传视频
	 */
	@Override
	public R uploadVideo(MultipartFile video) {

			String url = “xxxxxxxxxxx”;
			HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
			conn.setConnectTimeout(10*1000);
			conn.setConnectTimeout(5000);
			conn.setReadTimeout(30000);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
			conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + Boundary);

			DataOutputStream out = new DataOutputStream(conn.getOutputStream());
			//=============================模拟表单提交视频的核心===============top
			StringBuffer strBuf = new StringBuffer();
			strBuf.append("\r\n").append("--").append(Boundary).append("\r\n");
			strBuf.append("Content-Disposition: form-data; name=\"" + "video" + "\"; filename=\"" + video.getOriginalFilename() + "\"\r\n");
			strBuf.append("Content-Type:" + "video/mp4" + "\r\n\r\n");

			out.write(strBuf.toString().getBytes());

			byte[] b = new byte[1024];
			int l = 0;
			out.write(b); // 写入文件
			out.writeUTF("\r\n--"+Boundary+"--\r\n");
			out.flush();
			out.close();
			//=============================模拟表单提交视频的核心===============bottom
			BufferedReader result = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String s = null;
			StringBuilder r = new StringBuilder();
			while((s=result.readLine())!=null) {
				r.append(s);
			}
			
//			return R.error();
			
		}catch (Exception e){
			return R.error("异常================="+e);
		}
	}

原文链接:https://blog.csdn.net/weixin_43852094/article/details/11535179

你可能感兴趣的:(java,java,开发语言)