본문 바로가기
java

Java에서 Http 요청시 사용하는 방법

by chunkind 2023. 2. 27.
반응형
public static void main(String[] args) {
	////////////////////////방법1////////////////////////////////
    try{
        String url = "http://chunkind.com";
        org.apache.commons.httpclient.HttpClient httpclient = new org.apache.commons.httpclient.HttpClient(); 
        //System.out.println("Connection Url ::: "+url);
        org.apache.commons.httpclient.methods.PostMethod method = new org.apache.commons.httpclient.methods.PostMethod(url);
        //List<NameValuePair> params = toNameValuePair(bean);
        //method.setRequestBody(params.toArray(new NameValuePair[0]));

        int statusCode = httpclient.executeMethod(method);
        System.out.println("statusCode :: " + statusCode);
        if(200 == statusCode){
            System.out.println(method.getResponseBodyAsString());
        }else{
            throw new RuntimeException("Http Error Status Code ["+statusCode+"]");
        }
    }catch(Exception e){
        throw new RuntimeException(e);
    }
	////////////////////////방법2////////////////////////////////		
    HttpClient client = null;
    HttpPost httpPost = null;
    HttpResponse response = null;
    try{
        client = new DefaultHttpClient();
        HttpParams httpParam = client.getParams();
        int connectionTimeoutMillis = 1000 * 30;
        int socketTimeoutMillis = 1000 * 30;
        HttpConnectionParams.setConnectionTimeout(httpParam, connectionTimeoutMillis);
        HttpConnectionParams.setSoTimeout(httpParam, socketTimeoutMillis);
        httpPost = new HttpPost("http://chunkind.com");
        //CustomerBean bean = new CustomerBean();
        //bean.setAuthKey("fjeisfli");
        //bean.setAge(30);
        //List<NameValuePair> params = toNameValuePair(bean);
        //httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
        response = client.execute(httpPost);

        int httpStatus = response.getStatusLine().getStatusCode();
        System.out.println("HttpStatus : " + httpStatus);

        if(httpStatus != HttpStatus.SC_OK) {
            System.err.println( response.getStatusLine() );
            throw new Exception("Http Error Status Code ["+httpStatus+"]");
        }

        HttpEntity entity1 = response.getEntity();
        String str = EntityUtils.toString(entity1, "UTF-8");
        System.out.println(str);

        //ResponseHandler<String> rh = new BasicResponseHandler();
        //System.out.println(client.execute(httpPost, rh));
    }catch(Exception e){
        throw new RuntimeException(e);
    }
}
반응형