Developer Sang Guy

Java Http Rest 통신 소스 본문

Java

Java Http Rest 통신 소스

은크 2022. 1. 5. 22:00
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
 
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpOptions;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpTrace;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
 
public class Utils {
 
   private HttpUriRequest getHttpUriRequest(URI uri, String httpMethodName, String payload, String encoding)
            throws Exception {
 
        switch (httpMethodName) {
 
        case "GET":
            return new HttpGet(uri);
        case "POST":
            final HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(new StringEntity(payload, encoding));
            return httpPost;
        case "PUT":
            final HttpPut httpPut = new HttpPut(uri);
            httpPut.setEntity(new StringEntity(payload, encoding));
            return httpPut;
        case "PATCH":
            final HttpPatch httpPatch = new HttpPatch(uri);
            httpPatch.setEntity(new StringEntity(payload, encoding));
            return httpPatch;
        case "HEAD":
            return new HttpHead(uri);
        case "DELETE":
            final HttpDeleteWithBody httpDeleteWithBody = new HttpDeleteWithBody(uri);
            httpDeleteWithBody.setEntity(new StringEntity(payload, encoding));
            return httpDeleteWithBody;
        case "OPTIONS":
            return new HttpOptions(uri);
        case "TRACE":
            return new HttpTrace(uri);
        default:
            throw new Exception("Invalid HTTP method " + httpMethodName);
        }
    }
 
    public List<String> sendRequest(final URI uri, final Map<StringString> headers, final String payload, final String httpMethodName) throws Exception {
        
        final List<String> result = new ArrayList<>();
        final StringBuffer response = new StringBuffer();
        int responseCode = 0;
        
        try (final CloseableHttpClient client = HttpClients.createDefault()) {
            
            final HttpUriRequest httpUriRequest = getHttpUriRequest(uri, httpMethodName, payload, "UTF-8");
            for (Map.Entry<StringString> entry : headers.entrySet()) {
                httpUriRequest.addHeader(entry.getKey(), entry.getValue());
            }
            
            final HttpResponse responses = client.execute(httpUriRequest);
            responseCode = responses.getStatusLine().getStatusCode();
            if (responseCode < HttpURLConnection.HTTP_BAD_REQUEST) {
                String inputLine;
                
                try (final BufferedReader in = new BufferedReader(
                        new InputStreamReader(responses.getEntity().getContent(), "UTF-8"))) {
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine).append(System.lineSeparator());
                    }
                }
                
            } else {
                response.append(EntityUtils.toString(responses.getEntity()));
            }
        } catch (Exception e) {
            throw e;
        }
        result.add(String.valueOf(responseCode));
        result.add(response.toString());
        return result;
    }
}
cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.net.URI;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
 
/*
 * HTTPDelete Method doesn't support adding body in request.
 * This class is used to call HTTPDelete with request body
 */
public class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
 
    public static final String METHOD_NAME = "DELETE";
 
    public String getMethod() {
        return METHOD_NAME;
    }
 
    public HttpDeleteWithBody(final String uri) {
        super();
        setURI(URI.create(uri));
    }
 
    public HttpDeleteWithBody(final URI uri) {
        super();
        setURI(uri);
    }
 
    public HttpDeleteWithBody() {
        super();
    }
}
cs

'Java' 카테고리의 다른 글

데이터 압축  (0) 2022.05.26
[Java]NonStaticInnerClass vs StaticInnerClass  (0) 2022.05.18
Java Graphql Client 구현  (0) 2022.03.30
Java Singleton 객체 구현 및 주의 사항  (0) 2021.05.16
OCP (Open Close Principal) 개방 폐쇄 원칙  (0) 2021.05.14
Comments