public void run(){
httpclient = new DefaultHttpClient();
try {
HttpPost post = new HttpPost(address);
//헤더 설정
post.setHeader("Connection", "Keep-Alive");
post.setHeader("Accept-Charset", "UTF-8");
post.setHeader("ENCTYPE", "multipart/form-data");
//멀티파트 엔티티 생성, 파일 이름이 한글일 경우 Charset을 정하는 게 좋음
MultipartEntity multipartContent =
new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,
null, Charset.forName("UTF-8"));
//파일 붙임
FileBody cbFile = new FileBody(file);
multipartContent.addPart("file1", cbFile);
//파라메터
for(NameValuePair nvp:nameValues){
multipartContent.addPart(nvp.getName(),
new StringBody(URLEncoder.encode(nvp.getValue(), HTTP.UTF_8)));
}
//파일 사이즈
multipartContent.addPart("fileSize", new StringBody(String.valueOf(file.length())));
//HttpPost Entity에 연결
post.setEntity(multipartContent);
//10초 응답시간 타임아웃 설정
HttpParams params = httpclient.getParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpConnectionParams.setConnectionTimeout(params, 10000);
HttpConnectionParams.setSoTimeout(params, 10000);
//org.apache.http.client.HttpClient 로 실행
httpclient.execute(post, responseHandler);
} catch (ConnectTimeoutException e){
// 타임 아웃 연결 에러시
Message message = resultHandler.obtainMessage();
Bundle bundle = new Bundle();
bundle.putString(RESULT, TIMEOUT_RESULT);
message.setData(bundle);
resultHandler.sendMessage(message);
stringData = e.toString();
} catch (Exception e){
// 기타 오류시
Message message = resultHandler.obtainMessage();
Bundle bundle = new Bundle();
bundle.putString(RESULT, ERROR_RESULT);
message.setData(bundle);
resultHandler.sendMessage(message);
stringData = e.toString();
} finally {
httpclient.getConnectionManager().shutdown();
}
}
티스토리 파일업로드 api 멀티파트 설정 (java)