메뉴 건너뛰기

조회 수 1136 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄

정확하게는 모르지만 왠지 내가 알기론 Apache Commons HttpClient 후로젝트가 Apache HttpComponents 로 바뀐것 같다.


그러니까 최신 API 는 아마 Apache HttpComponents 이겠지...


그런데 왜 굳이 옛날 API 로 예제를 맹글게 되었을까..?


피치못할 사정으로 JDK 1.4 기반에서 동작하도록 해야했기 때문이다 -.-



나 같은 저주 받은 개발환경이 아닌 사람들은 이전에 썼던 포스트를 참고해서 고거 쓰면 된다.


뭐 아무튼 예제 소스는 요럿다.

package com.tistory.stove99;
 
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
 
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.lang.StringEscapeUtils;
 
 
public class Http {
    private static final String DEFAULT_ENCODING = "UTF-8";
     
    private String url;
    private String encoding;
    private Map param;
     
     
    public Http(String url){
        this(url, null);
    }
     
    public Http(String url, String encoding){
        this.encoding = encoding==null ? DEFAULT_ENCODING : encoding;
        this.url = url;
         
        param = new HashMap();
    }
     
    /**
     * Http 전송
     * @return
     */
    public String submit(){
        String result = null;
         
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod (url);
 
        try{
            Part[] parts = new Part[param.size()];
            Iterator it = param.keySet().iterator();
            int index = 0;
            while( it.hasNext() ){
                String key = (String)it.next();
                Object value = param.get(key);
                 
                if( value instanceof File ){
                    // 한글 파일명이 쪽바로 처리가 안되서 StringEscapeUtils 썻음.
                    // 받는 쪽에서는 StringEscapeUtils.unescapeHtml() 로 다시 변환바람.
                    parts[index++] = new FilePart(
                                            key, 
                                            StringEscapeUtils.escapeHtml(((File)value).getName()), 
                                            (File)value, 
                                            null, 
                                            encoding);
                }else{
                    parts[index++] = new StringPart(key, (String)value, encoding);
                }
            }
            method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
             
            client.executeMethod(method);
             
            // read result
            BufferedReader br = new BufferedReader(
                                        new InputStreamReader(method.getResponseBodyAsStream(), encoding));
            String buffer = null;
            StringBuffer tmp = new StringBuffer();
             
            while( (buffer=br.readLine())!=null ){
                tmp.append(buffer).append("\r\n");
            }
             
            result = tmp.toString();
        }catch (HttpException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            method.releaseConnection();
        }
         
        return result;
    }
     
    /**
     * 일반 파라메터 추가
     * @param name  파라메터 이름
     * @param value 값
     * @return
     */
    public Http addParam(String name, String value){
        param.put(name, value);
         
        return this;
    }
     
    /**
     * 업로드할 파일을 파라메터로 추가
     * @param name  <input type="file" name="요기들어가는 값"/>
     * @param file
     * @return
     */
    public Http addParam(String name, File file){
        param.put(name, file);
         
        return this;
    }
     
     
    /**
     * 테스트
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        Http http = new Http("http://127.0.0.1:8888/rpm/alarm/receive.kins");
        String result = http.addParam("test", "테스트다1")
                            .addParam("test1", "테스트다2")
                            .addParam("upload_file1", new File("d:\\야훗훗 유지보수.xlsx"))
                            .addParam("upload_file2", new File("d:\\휴가신청서.hwp"))
                            .submit();
         
        System.out.println("result : " + result);
    }
}


Maven Dependency


<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
</dependency>
<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency>



List of Articles
번호 제목 날짜 조회 수
51 로그인 컴포넌트 설치시 뷰 생성 에러 해결방법 (ORA-01031: 권한이 불충분합니다) file 2016.08.29 3874
50 개인정보 마스킹처리 (휴대폰번호, 이메일) 2018.06.26 3941
49 iBATIS 동적으로 맵핑하기 2016.12.09 3949
48 [자바(스프링&mybatis&jsp) 프로젝트 & 아파치 &톰켓 연동 ]11. 이클립스 프로젝트 생성 file 2016.08.18 3972
47 변수의 종류 2016.09.13 3978
46 프로젝트 & 아파치 &톰켓 연동 ]1. 폴더 만들기 file 2016.08.18 3983
45 [자바(스프링&mybatis&jsp) 프로젝트 & 아파치 &톰켓 연동 ]9. 이클립스 압타나 플러그인 설치 file 2016.08.18 4012
44 jquery 스크롤(scroll) 따라다니는 배너 레이어 / 위로 버튼 / 화면 상단으로 이동 / scroll layer 이벤트 file 2017.07.05 4057
43 Database Connections 생성하기 (오라클) file 2016.08.29 4072
42 war로 묶지 않아도 컴파일된 소스 위치 확인하기 file 2016.08.29 4116
41 Spring Boot 프로젝트 생성 file 2016.09.02 4160
40 프로젝트 & 아파치 &톰켓 연동 ]2. 자바 설치 file 2016.08.18 4170
39 eclipse 콘솔(로그)에 디버그(Debug) 모드에서 실행된 쿼리문을 보여주자. - 전자정부프레임워크 오라클 file 2016.08.29 4172
38 자바 다양한 형변환. 그리고 아스키 코드 String char int : JAVA 2016.12.09 4188
37 [자바(스프링&mybatis&jsp) 프로젝트 & 아파치 &톰켓 연동 ] 이클립스 프로젝트 생성 순서04.jdbc 드라이버 설치 file 2016.08.18 4209
36 전자정부 표준프레임워크 설치하기 file 2016.08.29 4250
35 배치관리 컴포넌트 생성 후 에러 날 때 해결방법 file 2016.08.29 4267
34 My-SQL 을 이용한 JDBC file 2016.09.21 4282
33 자바 JXL 엑셀파일을 읽어 배열리턴 : JAVA EXCEL ArrayList 2016.12.09 4389
32 이클립스를 화려하게 꾸며보자 file 2016.09.19 4457
Board Pagination Prev 1 2 3 4 5 6 7 8 Next
/ 8

하단 정보를 입력할 수 있습니다

© k2s0o1d4e0s2i1g5n. All Rights Reserved