1 package com.github.davidmoten.aws.lw.client.internal;
2
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.io.OutputStream;
6 import java.io.UncheckedIOException;
7 import java.net.HttpURLConnection;
8 import java.net.URL;
9 import java.util.List;
10 import java.util.Map;
11
12 import com.github.davidmoten.aws.lw.client.HttpClient;
13 import com.github.davidmoten.aws.lw.client.ResponseInputStream;
14 import com.github.davidmoten.aws.lw.client.internal.util.Util;
15
16 public final class HttpClientDefault implements HttpClient {
17
18 public static final HttpClientDefault INSTANCE = new HttpClientDefault();
19
20 private HttpClientDefault() {
21 }
22
23 @Override
24 public ResponseInputStream request(URL endpointUrl, String httpMethod,
25 Map<String, String> headers, byte[] requestBody, int connectTimeoutMs,
26 int readTimeoutMs) throws IOException {
27 HttpURLConnection connection = Util.createHttpConnection(endpointUrl, httpMethod, headers,
28 connectTimeoutMs, readTimeoutMs);
29 return request(connection, requestBody);
30 }
31
32
33 static ResponseInputStream request(HttpURLConnection connection, byte[] requestBody) {
34 int responseCode;
35 Map<String, List<String>> responseHeaders;
36 InputStream is;
37 try {
38 if (requestBody != null) {
39 OutputStream out = connection.getOutputStream();
40 out.write(requestBody);
41 out.flush();
42 }
43 responseHeaders = connection.getHeaderFields();
44 responseCode = connection.getResponseCode();
45 if (isOk(responseCode)) {
46 is = connection.getInputStream();
47 } else {
48 is = connection.getErrorStream();
49 }
50 if (is == null) {
51 is = Util.emptyInputStream();
52 }
53 } catch (IOException e) {
54 try {
55 connection.disconnect();
56 } catch (Throwable e2) {
57
58 }
59 throw new UncheckedIOException(e);
60 }
61 return new ResponseInputStream(connection, responseCode, responseHeaders, is);
62 }
63
64 private static boolean isOk(int responseCode) {
65 return responseCode >= 200 && responseCode <= 299;
66 }
67
68 }