>  기사  >  Java  >  Java의 `URLConnection`을 사용하여 파일 및 추가 매개변수를 업로드하는 방법은 무엇입니까?

Java의 `URLConnection`을 사용하여 파일 및 추가 매개변수를 업로드하는 방법은 무엇입니까?

Barbara Streisand
Barbara Streisand원래의
2024-10-25 02:18:02200검색

How to Upload Files and Additional Parameters with Java's `URLConnection`?

추가 매개변수를 사용하여 Java 클라이언트에서 HTTP 서버로 파일을 업로드하는 방법

HTTP POST 요청을 사용하여 Java 클라이언트에서 서버로 파일을 업로드할 때 일반적으로 발생하는 파일과 함께 추가 매개변수를 포함하고 싶습니다. 다음은 외부 라이브러리가 필요 없는 간단하고 효율적인 솔루션입니다.

java.net.URLConnection을 활용하여 HTTP 요청을 설정하고 바이너리 및 바이너리 모두를 처리하는 데 널리 사용되는 인코딩 형식인 다중 부분 양식 데이터에 대해 설정합니다. 텍스트 데이터. 다음은 추가 매개변수 매개변수와 textFile 및 BinaryFile 파일이 포함된 예입니다.

<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");

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 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 boundary
    writer.append("--" + boundary + "--").append(CRLF).flush();
}</code>

요청을 설정한 후 요청을 실행하고 응답 코드를 검색할 수 있습니다.

<code class="java">((HttpURLConnection) connection).getResponseCode();</code>

자세한 내용은 고급 시나리오를 사용하거나 프로세스를 단순화하려면 Apache Commons HttpComponents Client와 같은 타사 라이브러리를 사용하는 것이 좋습니다.

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

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