"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > java.net.URLConnection을 사용하여 파일 및 추가 매개변수를 HTTP 서버에 업로드하는 방법은 무엇입니까?

java.net.URLConnection을 사용하여 파일 및 추가 매개변수를 HTTP 서버에 업로드하는 방법은 무엇입니까?

2024-11-07에 게시됨
검색:843

How to upload files and additional parameters to an HTTP server using java.net.URLConnection?

Java의 추가 매개변수를 사용하여 HTTP 서버에 파일 업로드

HTTP 서버에 파일을 업로드하는 것은 많은 애플리케이션에서 공통적으로 필요합니다. 그러나 때로는 파일과 함께 추가 매개변수를 전달해야 하는 경우도 있습니다. 다음은 외부 라이브러리를 사용하지 않고 파일과 매개변수를 모두 보낼 수 있는 솔루션입니다.

java.net.URLConnection 및 Multipart/Form-Data

파일을 보내고 매개변수를 사용하려면 java.net.URLConnection을 활용하고 다중 부분/양식 데이터 인코딩을 사용합니다. Multipart/form-data를 사용하면 단일 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); 

추가 참고 사항:

  • 각 멀티파트 요청에 대해 고유한 경계 값을 제공해야 합니다.
  • 파일은 다음과 같은 경우 지정된 문자 세트에 있어야 합니다. Content-Type 헤더를 전송합니다.
  • Apache Commons HttpComponents 클라이언트는 프로세스를 더욱 간소화할 수 있지만 반드시 필요한 것은 아닙니다.

참조:

  • [java.net.URLConnection을 사용하여 HTTP 요청 실행 및 처리](https://docs.oracle.com/javase/tutorial/networking/urls/creating-urls.html)
최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3