벡엔드 담당자와 협업중 자바에서 php서버로 Multipart post를 필요로 하였다.
아래의 클래스를 사용하였으며, 라이브러리는
구아바?
구아바!
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import com.google.common.base.Strings;
import com.google.common.io.CharStreams;
public class MultipartUploader {
private static final String CHARSET = "UTF-8";
private static final String CRLF = "\r\n";
public String httpUpload(String url, String filename, byte[] byteStream)
throws MalformedURLException, IOException {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
final String boundary = Strings.repeat("-", 15) + Long.toHexString(System.currentTimeMillis());
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Cache-Control", "no-cache");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
OutputStream directOutput = connection.getOutputStream();
PrintWriter body = new PrintWriter(new OutputStreamWriter(directOutput, CHARSET), true);
body.append(CRLF);
addSimpleFormData("가나다라", "atㅋㅋㅋㅇㅇtach1", body, boundary); //텍스트 파라미터
addSimpleFormData("마바사", "6ㄴㅇㅁ", body, boundary); //텍스트 파라미터
addFileData("attach", filename, byteStream, body, directOutput, boundary);
addCloseDelimiter(body, boundary);
int responseCode = connection.getResponseCode();
String responseMessage = connection.getResponseMessage();
String payload = CharStreams.toString(new InputStreamReader(connection.getInputStream()));
return payload;
}
private static void addSimpleFormData(String paramName, String wert, PrintWriter body,
final String boundary) {
body.append("--").append(boundary).append(CRLF);
body.append("Content-Disposition: form-data; name=\"" + paramName + "\"").append(CRLF);
body.append("Content-Type: text/plain; charset=" + CHARSET).append(CRLF);
body.append(CRLF);
body.append(wert).append(CRLF);
body.flush();
}
private static void addFileData(String paramName, String filename, byte[] byteStream, PrintWriter body,
OutputStream directOutput, final String boundary) throws IOException {
body.append("--").append(boundary).append(CRLF);
body.append("Content-Disposition: form-data; name=\"" + paramName + "\"; filename=\"" + filename + "\"")
.append(CRLF);
body.append("Content-Type: application/octed-stream").append(CRLF);
body.append("Content-Transfer-Encoding: binary").append(CRLF);
body.append(CRLF);
body.flush();
directOutput.write(byteStream);
directOutput.flush();
body.append(CRLF);
body.flush();
}
private static void addCloseDelimiter(PrintWriter body, final String boundary) {
body.append("--").append(boundary).append("--").append(CRLF);
body.flush();
}
}
위의 파라미터 중 byteStream은
public static byte[] fileToBinary(File file) {
String out = new String();
byte[] fileArray = null;
FileInputStream fis = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e) {
System.out.println("Exception position : FileUtil - fileToString(File file)");
}
int len = 0;
byte[] buf = new byte[1024];
try {
while ((len = fis.read(buf)) != -1) {
baos.write(buf, 0, len);
}
fileArray = baos.toByteArray();
// out = new String(base64Enc(fileArray));
fis.close();
baos.close();
} catch (IOException e) {
System.out.println("Exception position : FileUtil - fileToString(File file)");
}
return fileArray;
}
public static byte[] base64Enc(byte[] buffer) {
return Base64.encodeBase64(buffer);
}
}
를 사용한다.
fileArray를 리턴하는데 내가 급하게 만든다고 필요없는 메서드가 있긴하다...
'프로그래밍 > Java & JSP' 카테고리의 다른 글
Dependency Injection 이란? (0) | 2020.09.12 |
---|