import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class SignByPathSender {
private static final int API_TIMEOUT = 300 * 1000; // 30 seconds
public static void main(String[] args) throws MalformedURLException {
URL url = new URL("http://localhost:8080/api/ext/signpdf"); //Aergo TSA서버의 주소로 변경
Map<String, String> params = new HashMap<>();
params.put("in", args[0]);
params.put("out", args[1]);
params.put("category", args[2]);
try {
byte[] result = postForm(url, params);
System.out.println("success: result file is in " + new String(result));
} catch (IllegalArgumentException e) {
String cause = e.getMessage(); // 서버쪽에서 알린 실패 이유
System.out.println("server response error: " + cause);
} catch (IOException e) {
String cause = e.getMessage();
System.out.println("unexpected failure: " + cause);
}
}
private static byte[] postForm(URL url, Map<String, String> params) throws IllegalArgumentException, IOException {
try {
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(API_TIMEOUT); //서버에 연결되는 Timeout 시간 설정
con.setReadTimeout(API_TIMEOUT); // InputStream 읽어 오는 Timeout 시간 설정
con.setRequestMethod("POST"); //POST 방식 선언
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //content-type 선언
con.setDoInput(true);
con.setDoOutput(true); //POST 데이터를 OutputStream으로 넘겨 주겠다는 설정
con.setUseCaches(false);
con.setDefaultUseCaches(false);
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> ent : params.entrySet()) {
sb.append(ent.getKey()).append('=').append(URLEncoder.encode(ent.getValue(), "UTF-8"));
sb.append('&');
}
sb.deleteCharAt(sb.length() - 1);
con.getOutputStream().write(sb.toString().getBytes());
con.getOutputStream().flush();
if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
byte[] bytes = readToByteArray(con.getInputStream());
return bytes;
} else {
int responseCode = con.getResponseCode();
byte[] bytes = readToByteArray(con.getErrorStream());
throw new IllegalArgumentException(new String(bytes));
}
} catch (IOException e) {
// FIXME
throw new IOException("io exception", e);
}
}
private static byte[] readToByteArray(InputStream is) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[4096];
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
return buffer.toByteArray();
}
}