본문 바로가기

Dev Ref/Java

JAVA HTTP 통신 PDF파일 송수신

HttpURLConnection을 이용한 파일 송수신



Issue01 : box01 폴더에 sample01.pdf파일을 server box02에 저장한다.


Issue02 : box02 폴더에 sample02.pdf 파일을 요청하여 box01에 저장한다.



## 패키지 이미지






1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
 
public class client {
 
    // String args[(put,get),(sample01,sample02)]
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
 
        // args 값이 없을 때 입력을 받는다.
        if (args.length == 0) {
            args = new String[2];
 
            System.out.print("put/get : ");
            args[0= sc.next();
 
            if (args[0].toLowerCase().equals("put")) {
                System.out.print("전달 할 파일명을 기입하시오 : ");
                args[1= sc.next();
            } else if (args[0].toLowerCase().equals("get")) {
                System.out.print("가져 올  파일명을 기입하시오 : ");
                args[1= sc.next();
            }
 
            // 파라미터값의 수가 초과 되었거나 부족할때
        } else if (args.length != 2 && args.length != 0) {
            System.out.println("파라미터 값이 올바르지 않습니다.");
            return;
        }
 
        byte[] temp = new byte[2048];
        
        int length = 0;
        
        // 분기에 따른 클라이언트의 요구사항
        if (args[0].equals("put")) {
            // 전달할 파일의 데이터 읽어 오기
            String filePath = "D:/workbench/ClientSample_02/box01/" + args[1+ ".pdf";
 
            // 파일객체에 파일의 경로를 넣어준다
            File file = new File(filePath);
 
            // 파일을 읽을 수 있게 inputStream이랑 연결 시켜준다
            FileInputStream fis = new FileInputStream(file);
            
            OutputStream os = null;
            InputStream is = null;
            
            // 파일이 도달할 목표 주소설정
            URL url = new URL("http://localhost:8080/server/test");
 
            // URL과 연결한 객체생성(target url과 마주할 담당자이다.)
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
 
            // outputStream으로 서버로 데이터 전송
            try {
                // 담당자의 권한을 설정해 준다.
                con.setRequestMethod("POST"); // GET방식으로 사용한다
                con.setDoInput(true); // 읽기모드 활성
                con.setDoOutput(true); // 쓰기모드 활성
                con.setRequestProperty("type", args[0]); // 헤더로 데이터 전송
                con.setRequestProperty("fileName", args[1]); // 헤더로 데이터 전송
 
                os = con.getOutputStream();
 
                while ((length = fis.read(temp)) > 0) {
                    os.write(temp, 0length);
                }
                is = con.getInputStream();
                // success msg
                System.out.println(con.getHeaderField("msg"));
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                os.close();
                is.close();
                fis.close();
                con.disconnect();
            }
 
        } else if (args[0].equals("get")) {
            // 받고자 하는 파일이 저장 될 경로와 파일명
            String filePath = "./box01/" + args[1+ ".pdf";
 
            // 파일을 읽어들이기 위한 중간매개체
            InputStream is = null;
 
            // 파일을 보내기 위한 중간매개체
            FileOutputStream fos = new FileOutputStream(filePath);
 
            // 파일이 도달할 목표 주소설정
            URL url = new URL("http://localhost:8080/server/test");
 
            // URL과 연결한 객체생성(target url과 마주할 담당자이다.)
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
 
            try {
                // 담당자의 권한을 설정해 준다.
                con.setRequestMethod("POST"); // GET방식으로 사용한다
                con.setDoInput(true); // 읽기모드 활성
                con.setDoOutput(true); // 쓰기모드 활성
                con.setRequestProperty("type", args[0]); // 헤더로 데이터 전송
                con.setRequestProperty("fileName", args[1]); // 헤더로 데이터 전송
 
                // input스트림 개방 ?
                is = con.getInputStream();
 
                while ((length = is.read(temp)) > 0) {
                    fos.write(temp, 0length);
                }
                
                System.out.println("check");
                
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                is.close();
                fos.close();
                con.disconnect();
            }
        }
    }
 
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package server;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class serverController extends HttpServlet {
 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doProcess(req, resp);
    }
 
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doProcess(req, resp);
    }
 
    public void doProcess(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // initialize
        FileInputStream fis = null;
        FileOutputStream fos = null;
        InputStream is = null;
        OutputStream os = null;
        int length = 0;
        String header = "";
 
        // getHeaderData
        if (req.getHeader("type"!= null) {
            header = req.getHeader("type");
            System.out.println("getHeaderData : " + header);
        }
 
        // ?
        byte[] temp = new byte[2048];
 
        // branchPoint
        if (header.equals("put")) {
            // InputStream으로 body로 넘어온 데이터를 읽어온다.
            is = req.getInputStream();
 
            // 읽어온 파일의 저장경로와 저장할 파일명을 기입해준다.
            String reposiPath = "D:/workbench/server/box02/" + req.getHeader("fileName"+ ".pdf";
 
            // 파일객체에 저장할 파일의 경로값을 넣어준다.
            File file = new File(reposiPath);
 
            //
            try {
                fos = new FileOutputStream(file);
                while ((length = is.read(temp)) > 0) {
                    fos.write(temp, 0length);
                }
                // success msg
                resp.addHeader("msg""success");
                
            } catch (IOException e) {
                // false msg
                resp.addHeader("msg""false");
                e.printStackTrace();
            } finally {
                is.close();
                fos.close();
            }
        } else if (header.equals("get")) {
            // file name
            String fileName = "/" + req.getHeader("fileName"+ ".pdf";
            System.out.println("getHeader fileName : " + fileName);
 
            // getRealPath
            String contextPath = getServletContext().getRealPath(File.separator);
 
            // 파일의 진짜 경로를 넣어준다.
            File file = new File(contextPath + fileName);
 
            // 파일을 인풋 스트리밍 할 수 있게 파일경로가 담긴 파일을 넣어준다.
            fis = new FileInputStream(file);
 
            // 파일을 읽고 읽어드린 파일의 내용을 outputStream에 넣어준다.
            try {
                os = resp.getOutputStream();
                while ((length = fis.read(temp)) > 0) {
                    os.write(temp, 0length);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                fis.close();
                os.close();
            }
        }
    }
}
 
cs