/**
* 模拟form表单的形式 ,上传文件 以输出流的形式把文件写入到url中,然后用输入流来获取url的响应
*
* @param url 请求地址 form表单url地址
* @param filePath 文件在服务器保存路径
* @return String url的响应信息返回值
* @throws IOException
*/
public static RestResponse filePost(String url, String filePath){
String result = null;
File file = new File(filePath);
RestResponse restResponse = new RestResponse();
try {
if (!file.exists() || !file.isFile()) {
throw new IOException("文件不存在");
}
URL urlObj = new URL(url);
// 连接
HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
/**
* 设置关键值
*/
con.setRequestMethod("POST"); // 以Post方式提交表单,默认get方式
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false); // post方式不能使用缓存
// 设置请求头信息
con.setRequestProperty("charset", "UTF-8");
con.setRequestProperty("accept", "application/json");
con.setRequestProperty("Content-length", String.valueOf(file.length()));
// 设置边界
String BOUNDARY = "----------" + System.currentTimeMillis();
con.setRequestProperty("Content-Type", "multipart/form-data; boundary="+ BOUNDARY);
// 请求正文信息
// 第一部分:
StringBuilder sb = new StringBuilder();
sb.append("--"); // 必须多两道线
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"file\";filename=\""
+ file.getName() + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] head = sb.toString().getBytes("utf-8");
// 获得输出流
OutputStream out = new DataOutputStream(con.getOutputStream());
// 输出表头
out.write(head);
// 文件正文部分
// 把文件已流文件的方式 推入到url中
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);
}
in.close();
// 结尾部分
byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
out.write(foot);
out.flush();
out.close();
BufferedReader reader = null;
try {
//返回值
int resultCode = con.getResponseCode();
restResponse.setCode(resultCode);
restResponse.setMessage(con.getResponseMessage());
restResponse.setResponseBody(result);
} catch (IOException e) {
restResponse.setCode(HttpStatus.GONE.value());
restResponse.setMessage(e.toString());
logger.error(e.toString());
} finally {
if (reader != null) {
reader.close();
}
}
}catch (IOException e2){
restResponse.setCode(HttpStatus.GONE.value());
restResponse.setMessage(e2.toString());
logger.error(e2.toString());
}
return restResponse;
}
public static void main(String[] args) throws IOException {
String filePath = "D:/logs/logs2.log";
String sendUrl = "http://127.0.0.1:30014/api/v1/fileSystem/io" +
"?path=hdfs://nameservice1/tmp/CGC/userFile/tmp/CGC/jobs/ff939a74-f8b9-45f2-8b6c-6e2f4a0e5efb/logs3.log&chunkSize=16384&overwrite=true";
HttpRequestUtil fileUpload = new HttpRequestUtil();
fileUpload.filePost(sendUrl,filePath);
}