package jmeter;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import static java.lang.System.currentTimeMillis;
public class postupload_function {
public int postSend(String url, String filePath) throws IOException {
File file = new File(filePath);
if (!file.exists() || !file.isFile()) {
return -1;
}
URL urlObj = new URL(url);
HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
// 设置关键值
con.setRequestMethod("POST");
// 设置响应流和输出流
con.setDoInput(true);
con.setDoOutput(true);
// 不能缓存
con.setUseCaches(false);
// 设置请求头信息
con.setRequestProperty(
"",
"");
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
// 设置边界
String BOUNDARY = "----------" + currentTimeMillis();
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
// 请求正文信息
OutputStream out = new DataOutputStream(con.getOutputStream());
StringBuilder sb1;
sb1 = new StringBuilder();
sb1.append("--");
sb1.append(BOUNDARY);
sb1.append("\r\n");
sb1.append("--")
.append(BOUNDARY)
.append("\r\n")
.append("Content-Disposition: form-data; name=\"type\"")
.append("\r\n\r\n1")
.append("\r\n");
sb1.append("--")
.append(BOUNDARY)
.append("\r\n")
.append("Content-Disposition: form-data; name=\"name\"")
.append("\r\n\r\n测试探针0001")
.append("\r\n");
sb1.append("--")
.append(BOUNDARY)
.append("\r\n")
.append("Content-Disposition: form-data; name=\"remark\"")
.append("\r\n\r\n简介测试")
.append("\r\n");
byte[] head = sb1.toString().getBytes(StandardCharsets.UTF_8);
out.write(head);
StringBuilder sb;
sb = new StringBuilder();
sb.append("--")
.append(BOUNDARY)
.append("\r\n")
.append("Content-Disposition: form-data; name=\"probeFile\"; filename=\"")
.append(file.getName())
.append("\"\r\n")
.append("Content-Type: application/vnd.ms-excel\r\n\r\n");
byte[] head1 = sb.toString().getBytes(StandardCharsets.UTF_8);
out.write(head1);
// 文件正文部分
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes;
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(StandardCharsets.UTF_8); // 定义最后数据分隔线
out.write(foot);
out.flush();
out.close();
int code = con.getResponseCode();
System.out.println(String.valueOf(code));
System.out.println(con.getResponseMessage());
// 获取响应流
InputStream inputStream = con.getInputStream();
BufferedReader buffered = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String responseString = buffered.readLine();
System.out.println(responseString);
return code;
}
public static void main(String[] args) throws IOException {
postupload_function btl = new postupload_function();
System.out.println(
btl.postSend(
"https:",
""));
}
}