HTTP POST 를 이용한 파일 전송하기

httpclient 를 이용한 POST 파일, 이미지 전송

프로젝트를 진행 하며 클라이언트가 파일업로드를 하면

파일을 서버에서 PDF로 변환 한뒤, 다시 클라이언트 리다이렉트 해주는 로직을 

구현하고 있습니다. 자바의 org.apache 를 이용하여 post 방식으로 

파일을 서버에 전송하는 소스파일 입니다.


HTTP POST 를 이용한 파일 전송하기


import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class FileClient {
	public static void main(String args[]) {
	}
	public void fileServer(String rootPath, String fileName) {

		try {
			HttpClient httpclient = HttpClientBuilder.create().build();

			// xml파일을 수신할 서버주소
			HttpPost httppost = new HttpPost("http://localhost:7070/Test.jsp");
			StringBuffer fileData = new StringBuffer(1000);
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					new FileInputStream(rootPath +	fileName), "utf-8"));
			System.out.println("저장경로 = " + rootPath + fileName);
			char[] buf = new char[1024];
			int numRead = 0;
			while ((numRead = reader.read(buf)) != -1) {
				fileData.append(buf, 0, numRead);
			}
			reader.close();
			String xml_string_to_send = fileData.toString();
			StringEntity string_entity = new StringEntity(xml_string_to_send,"UTF-8");
			string_entity.setContentType("application/x-www-form-urlencoded");
			httppost.setEntity(string_entity);
			HttpResponse httpResponse = httpclient.execute(httppost);
			System.out.println("Response Code : "+ httpResponse.getStatusLine().getStatusCode()+ "    Response StatusLine : "
					+ httpResponse.getStatusLine());

			HttpEntity response_entity = httpResponse.getEntity();
			String response_string = EntityUtils.toString(response_entity);
			System.out.println(response_string);

		} catch (Throwable t) {
			t.printStackTrace();
		}
	}
}


이 글을 공유하기

댓글

Designed by JB FACTORY