تحميل الملفات إلى خادم HTTP مع معلمات إضافية في Java
يعد تحميل الملفات إلى خادم HTTP ضرورة شائعة للعديد من التطبيقات. ومع ذلك، في بعض الأحيان يكون من الضروري أيضًا تمرير معلمات إضافية مع الملفات. إليك الحل الذي يسمح لك بإرسال كل من الملفات والمعلمات دون استخدام مكتبات خارجية:
java.net.URLConnection and Multipart/Form-Data
لإرسال الملفات و المعلمات، ستستخدم java.net.URLConnection وتوظف ترميز بيانات متعدد الأجزاء/النماذج. تتيح لك بيانات النموذج/الأجزاء المتعددة مزج البيانات الثنائية (الملفات) وبيانات الأحرف (المعلمات) في طلب HTTP واحد.
مثال على الكود:
String url = "http://example.com/upload";
String charset = "UTF-8";
String param = "value";
File textFile = new File("/path/to/file.txt");
File binaryFile = new File("/path/to/file.bin");
String boundary = Long.toHexString(System.currentTimeMillis());
String CRLF = "\r\n";
URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" boundary);
try (
OutputStream output = connection.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
) {
// Send normal param.
writer.append("--" boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF);
writer.append("Content-Type: text/plain; charset=" charset).append(CRLF);
writer.append(CRLF).append(param).append(CRLF).flush();
// Send text file.
writer.append("--" boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"textFile\"; filename=\"" textFile.getName() "\"").append(CRLF);
writer.append("Content-Type: text/plain; charset=" charset).append(CRLF);
writer.append(CRLF).flush();
Files.copy(textFile.toPath(), output);
output.flush();
writer.append(CRLF).flush();
// Send binary file.
writer.append("--" boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" binaryFile.getName() "\"").append(CRLF);
writer.append("Content-Type: " URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF);
writer.append("Content-Transfer-Encoding: binary").append(CRLF);
writer.append(CRLF).flush();
Files.copy(binaryFile.toPath(), output);
output.flush();
writer.append(CRLF).flush();
// End of multipart/form-data.
writer.append("--" boundary "--").append(CRLF).flush();
}
// Request is lazily fired whenever you need to obtain information about response.
int responseCode = ((HttpURLConnection) connection).getResponseCode();
System.out.println(responseCode);
ملاحظات إضافية:
تنصل: جميع الموارد المقدمة هي جزئيًا من الإنترنت. إذا كان هناك أي انتهاك لحقوق الطبع والنشر الخاصة بك أو الحقوق والمصالح الأخرى، فيرجى توضيح الأسباب التفصيلية وتقديم دليل على حقوق الطبع والنشر أو الحقوق والمصالح ثم إرسالها إلى البريد الإلكتروني: [email protected]. سوف نتعامل مع الأمر لك في أقرب وقت ممكن.
Copyright© 2022 湘ICP备2022001581号-3