java 模擬表單方式提交上傳文件



/**
* 模擬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);
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM