본문 바로가기
개발/java,spring,springboot

Apache http request 응용(+Springboot)

by 개발자종혁 2021. 4. 22.
728x90

build.gradle

plugins {
    id 'org.springframework.boot' version '2.4.2'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
    mavenCentral()
}

dependencies {


    implementation 'org.springframework.boot:spring-boot-starter-web'

    // http client
    implementation 'org.apache.httpcomponents:httpclient'

    annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

test {
    useJUnitPlatform()
}

ApacheRequestUtil.java


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.example.sender.exception.ApiCallException;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

import lombok.extern.slf4j.Slf4j;

public abstract class ApacheRequestUtil {

    ObjectMapper objectMapper = new ObjectMapper();

    private final String baseUrl;

    public ApacheRequestUtil(){
        this.baseUrl = "";
    }
    public ApacheRequestUtil(String baseUrl){
        this.baseUrl = baseUrl;
    }


    public void get(String subUrl) throws Exception {


        // 2. set url of request
        HttpGet get = new HttpGet(baseUrl + subUrl);

        callRequest(get);
    }

    // @formatter:off
    public void get(String subUrl, Map<String, String> headers, Map<String, String> params) throws ApiCallException, UnsupportedOperationException, IOException, URISyntaxException {

        // 2. set url of request
        HttpGet get = new HttpGet(baseUrl+subUrl);

        // 3. set params
        if(params != null){
            List<NameValuePair> paramList = new ArrayList<NameValuePair>();

            params.entrySet().forEach(set ->{
                paramList.add(new BasicNameValuePair(set.getKey(), set.getValue()));
            });
            URI uri = new URIBuilder(get.getURI()).addParameters(paramList).build();
            get.setURI(uri);
        }


        if(headers !=null){

            // 4. set headers of post request
            headers.entrySet().forEach(set ->{
                get.setHeader(set.getKey(), set.getValue());
            });
        }

        callRequest(get);

    }

    public void post(String subUrl, Map<String, String> headers, Map<String, String> body) throws ApiCallException, UnsupportedOperationException, IOException {

        // 2. set url of request
        HttpPost post = new HttpPost(baseUrl+subUrl);

        // 3. set body


        if(body != null){
            List<NameValuePair> bodyList = new ArrayList<NameValuePair>();

            body.entrySet().forEach(set ->{
                bodyList.add(new BasicNameValuePair(set.getKey(), set.getValue()));
            });


            post.setEntity(new UrlEncodedFormEntity(bodyList));
        }

        // set headers
        headers.forEach((key, value)->{ 
            post.setHeader(key, value);
        });

        callRequest(post);

    }
    private void callRequest(HttpRequestBase req) throws ApiCallException, UnsupportedOperationException, IOException {
        // 5. call request
        try (CloseableHttpClient httpClient = HttpClients.createDefault(); 
             CloseableHttpResponse response = httpClient.execute(req)) {
            int status = response.getStatusLine().getStatusCode();

            String text = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8))
                    .lines()
                    .collect(Collectors.joining("\n"));

            if(status != 200){
                throw new ApiCallException("status code:"+status);
            }


        }
        catch (ApiCallException | UnsupportedOperationException | IOException e) {
            throw e;
        }
    }

    public void postJson(String subUrl, Map<String, String> headers, Map<String, String> body) throws ApiCallException, UnsupportedOperationException, IOException {

        // 2. set url of request
        HttpPost post = new HttpPost(baseUrl+subUrl);

        // 3. set body


        if(body != null){
            StringEntity entity = new StringEntity(objectMapper.writeValueAsString(body));
            post.setEntity(entity);
        }

        // set headers as json
        if(headers == null){
            headers = new HashMap<>();
        }
        headers.put("Content-type", "application/json");
        headers.put("Accept", "application/json");

        // set headers
        headers.forEach((key, value)->{
            post.setHeader(key, value);
        });

        callRequest(post);

    }
}

ApiCallException.java

public class ApiCallException extends RuntimeException {

    private static final long serialVersionUID = -5289087194087192068L;

    public ApiCallException() {
    }

    public ApiCallException(String message) {
        super(message);
    }

    public ApiCallException(String message, Throwable cause) {
        super(message, cause);
    }

    public ApiCallException(Throwable cause) {
        super(cause);
    }

    public ApiCallException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

SlackRequestUtil.java

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Component

public class SlackRequestUtil extends ApacheRequestUtil{


    public SlackRequestUtil(@Value("${webhook_url}") String webhookUtil) {

        super(webhookUtil);
    }


}

application.yml


...

webhook_url: https://hooks.slack.com/services/xxx/xxx

...

728x90

댓글