java http post写真
20865 ワード
java http post写真ファイル、参考文章https://blog.csdn.net/yjclsx/article/details/70675057
/**
* URL
*
* @param fileName
* @param urlStr
* @return
*/
public static String uploadFile(String urlStr, String deviceId, File file) {
try {
//
final String NEWLINE = "\r
";
final String BOUNDARY = "----brujarBoundaryari0emH33oMihIU4";
//
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// POST
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
//
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36");
conn.connect();
OutputStream out = new DataOutputStream(conn.getOutputStream());
//
StringBuilder sb1 = new StringBuilder();
sb1.append("--");
sb1.append(BOUNDARY);
sb1.append(NEWLINE);
sb1.append("Content-Disposition: form-data; name=\"deviceId\"");
sb1.append(NEWLINE);
sb1.append(NEWLINE);
sb1.append(deviceId);
sb1.append(NEWLINE);
out.write(sb1.toString().getBytes());
//
StringBuilder sb = new StringBuilder();
sb.append("--");
sb.append(BOUNDARY);
sb.append(NEWLINE);
sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"");
sb.append(NEWLINE);
sb.append("Content-Type:application/octet-stream");
sb.append(NEWLINE);
sb.append(NEWLINE);
//
out.write(sb.toString().getBytes());
// ,
DataInputStream in = new DataInputStream(new FileInputStream(file));
byte[] bufferOut = new byte[2048];
int bytes = 0;
// 2KB ,
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
//
out.write(NEWLINE.getBytes());
in.close();
// , -- BOUNDARY --。
byte[] end_data = (NEWLINE + "--" + BOUNDARY + "--" + NEWLINE).getBytes();
//
out.write(end_data);
out.flush();
out.close();
// BufferedReader URL
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream(), "UTF-8"));
StringBuffer buffer = new StringBuffer();
String line = null;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} catch (Exception e) {
System.out.println(" POST !" + e);
e.printStackTrace();
}
return "";
}
public static void main(String[] args) {
String url = "http://127.0.0.1:8880/api";
String filePath = "D:\\11.jpg";
String result = uploadFile(url, "hgfuuyitygcfyri", new File(filePath));
System.out.println(result);
}
印刷結果は、成功したら画像のプレビューアドレスに戻ります。今後はプレビューアドレスを遮断します。他の用途にはしないでください。