JAVA

Java 대용량 데이터 청크로 분리해서 데이터 전송하기

Machine_웅 2023. 3. 10. 14:01
728x90
반응형
import java.io.*;
import java.net.*;

public class LargeDataSender {
    public static void main(String[] args) throws Exception {
        // 대상 서버와 포트 설정
        String host = "example.com";
        int port = 80;

        // 데이터를 보낼 파일 경로 설정
        String filePath = "/path/to/largefile.txt";
        File file = new File(filePath);

        // HTTP 요청 생성
        URL url = new URL("http://" + host + ":" + port + "/upload");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/octet-stream");
        connection.setRequestProperty("Transfer-Encoding", "chunked");

        // 파일 입력 스트림 생성
        FileInputStream fileInputStream = new FileInputStream(file);
        
        // 또는  InputStream targetStream = new ByteArrayInputStream(바이트배열); 로 inputstream

        // 출력 스트림 생성
        OutputStream outputStream = connection.getOutputStream();

        // 파일 내용을 작은 조각으로 나누어서 출력 스트림으로 전송
        byte[] buffer = new byte[4096];
        int bytesRead = -1;
        while ((bytesRead = fileInputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }

        // 스트림을 닫음
        fileInputStream.close();
        outputStream.close();

        // 서버 응답 확인
        int responseCode = connection.getResponseCode();
        System.out.println("Response Code: " + responseCode);
    }
}
728x90
반응형

'JAVA' 카테고리의 다른 글

JDK 설치 - 시스템 환경변수 설정  (0) 2024.03.04
Java ) DataInputStream  (0) 2023.02.17
시스템 환경의 Endian (엔디안) 종류 체크  (0) 2023.01.05
Java) InputStream  (0) 2022.12.22
2차원 배열 4배수  (0) 2022.12.14