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

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

Mary-Kate Olsen
Mary-Kate Olsen원래의
2024-10-25 03:02:30181검색

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 요청에서 바이너리 데이터(파일)와 문자 데이터(매개변수)를 혼합할 수 있습니다.

예제 코드:

<code class="java">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); </code>

추가 참고 사항:

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

참조:

  • [사용 HTTP 요청을 실행하고 처리하기 위한 java.net.URLConnection](https://docs.oracle.com/javase/tutorial/networking/urls/creating-urls.html)

위 내용은 java.net.URLConnection을 사용하여 파일 및 추가 매개변수를 HTTP 서버에 업로드하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.