How can I make a multipart/form-data POST request using Java?

@see
http://stackoverflow.com/questions/1378920/how-can-i-make-a-multipart-form-data-post-request-using-java

1. maven dependancy
    
  
        org.apache.httpcomponents
        httpcore
        4.2.5
    
    
        org.apache.httpcomponents
        httpclient
        4.2.5
    
    
       org.apache.httpcomponents
       httpmime
       4.2.5
    
2. source
package sample;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

/**
 * multipart request 
 * 
 */
public class SampleHttpConnector implements InitializingBean, DisposableBean {

 protected Log log = LogFactory.getLog(this.getClass());

 protected int connectionTimeout = 6000;

 protected int socketTimeout = 6000;

 protected int maxConnectionCount = 50;

 protected int maxConnectionPerRoute = 10;

 protected HttpClient httpClient;

 protected Map<String,String> headerMap;

 protected String encoding = "UTF-8";

 protected String contentType = "application/x-www-form-urlencoded; charset=utf-8";

 public void setSocketTimeout(int socketTimeout) {
  this.socketTimeout = socketTimeout;
 }

 public void setConnectionTimeout(int connectionTimeout) {
  this.connectionTimeout = connectionTimeout;
 }

 public void setMaxConnectionCount(int maxConnectionCount) {
  this.maxConnectionCount = maxConnectionCount;
 }

 public void setMaxConnectionPerRoute(int maxConnectionPerRoute) {
  this.maxConnectionPerRoute = maxConnectionPerRoute;
 }

 public void setEncoding(String encoding) {
  this.encoding = encoding;
 }

 public void setContentType(String contentType) {
  this.contentType = contentType;
 }

 public void setHeaderMap(Map<String,String> headerMap) {
  this.headerMap = headerMap;
 }

 public void afterPropertiesSet() throws Exception {
  HttpParams httpParams = new BasicHttpParams();
  httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT,
    socketTimeout);
  httpParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
    connectionTimeout);

  SchemeRegistry schemeRegistry = new SchemeRegistry();
  schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory
    .getSocketFactory()));
  schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory
    .getSocketFactory()));

  PoolingClientConnectionManager clientConnectionManager = new PoolingClientConnectionManager(
    schemeRegistry);
  clientConnectionManager.setMaxTotal(maxConnectionCount);
  clientConnectionManager.setDefaultMaxPerRoute(maxConnectionPerRoute);

  httpClient = new DefaultHttpClient(clientConnectionManager, httpParams);
 }

 public void destroy() throws Exception {
  httpClient.getConnectionManager().shutdown();
 }

 /**
  * multipart형식의 전송
  * 
  * @param params
  *            body parameters
  * @param targetUrl
  *            target remote url
  * @param is
  *            InputStream
  * @param fileName
  *            file name
  * @return
  * @throws IOException
  */
 public String sendMultipart(Map<String,String> params, String targetUrl,
   InputStream is, String fileName) throws IOException {

  HttpPost httpPost = new HttpPost(targetUrl);

  // 헤더값 설정
  for (Map.Entry<String,String> entry : headerMap.entrySet()) {
   httpPost.setHeader(entry.getKey(), entry.getValue());
  }
  // multipart entity
  MultipartEntity entity = new MultipartEntity();
  InputStreamBody body = new InputStreamBody(is, fileName);
  entity.addPart("file", body);
  // 파라미터 설정
  if (params != null) {
   if (log.isDebugEnabled()) {
    log.debug("Post param=" + params);
   }
   for (Map.Entry<String,String> entry : params.entrySet()) {
    entity.addPart(entry.getKey(), new StringBody(entry.getValue(),
      Charset.forName(encoding)));
   }
  }
  httpPost.setEntity(entity);

  // 전송
  HttpResponse httpResponse = httpClient.execute(httpPost);
  // 응답 처리
  HttpEntity responseEntity = httpResponse.getEntity();
  ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  if (responseEntity != null) {
   responseEntity.writeTo(outputStream);
  }

  if (httpResponse.getStatusLine().getStatusCode() != 200) {
   // Not '200 OK'
   throw new IOException("Fail to send HTTP Post : Status Code = "
     + httpResponse.getStatusLine());
  }
  return outputStream.toString();
 }

 // for test
 public static void main(String[] args) throws Exception {

  SampleHttpConnector adapter = new SampleHttpConnector();
  adapter.afterPropertiesSet();

  Map<String,String> headerMap = 
                         new java.util.HashMap<String,String>();
  headerMap.put("key1", "value1");
  headerMap.put("key2", "value2");
  adapter.setHeaderMap(headerMap);

  String targetUrl = "http://remote-host:8080/upload";
  InputStream is = new java.io.FileInputStream("d:/tmp/ddd.png");
  String fileName = "ddd.png";

    Map<String,String> bodyMap = 
                         new java.util.HashMap<String,String>();
  bodyMap.put("key1", "value1");
  bodyMap.put("key2", "value2");
  String result = adapter.sendMultipart(bodyMap, targetUrl, is, fileName);
  System.out.println("[result]=" + result );

 }

}

댓글

이 블로그의 인기 게시물

Charset 변환 ( EUC-KR, UTF-8, MS949, CP933 )

GZipUtils- gzip을 통한 압축시 charset처리

ESAPI ( XSS, Sql Injection )