|
| 1 | +package cn.jiguang.common.connection; |
| 2 | + |
| 3 | +import cn.jiguang.common.ClientConfig; |
| 4 | +import cn.jiguang.common.resp.APIConnectionException; |
| 5 | +import cn.jiguang.common.resp.APIRequestException; |
| 6 | +import cn.jiguang.common.resp.ResponseWrapper; |
| 7 | +import okhttp3.*; |
| 8 | +import org.slf4j.Logger; |
| 9 | +import org.slf4j.LoggerFactory; |
| 10 | + |
| 11 | +import java.io.IOException; |
| 12 | +import java.io.UnsupportedEncodingException; |
| 13 | +import java.net.Authenticator; |
| 14 | +import java.text.MessageFormat; |
| 15 | +import java.util.concurrent.TimeUnit; |
| 16 | + |
| 17 | + |
| 18 | +public class Http2Client implements IHttpClient { |
| 19 | + |
| 20 | + private static final Logger LOG = LoggerFactory.getLogger(Http2Client.class); |
| 21 | + private static final String KEYWORDS_CONNECT_TIMED_OUT = "connect timed out"; |
| 22 | + private static final String KEYWORDS_READ_TIMED_OUT = "Read timed out"; |
| 23 | + public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); |
| 24 | + |
| 25 | + private final int _connectionTimeout; |
| 26 | + private final int _readTimeout; |
| 27 | + private final int _maxRetryTimes; |
| 28 | + private final String _sslVer; |
| 29 | + |
| 30 | + private String _authCode; |
| 31 | + private HttpProxy _proxy; |
| 32 | + |
| 33 | + public Http2Client(String authCode, HttpProxy proxy, ClientConfig config) { |
| 34 | + _maxRetryTimes = config.getMaxRetryTimes(); |
| 35 | + _connectionTimeout = config.getConnectionTimeout(); |
| 36 | + _readTimeout = config.getReadTimeout(); |
| 37 | + _sslVer = config.getSSLVersion(); |
| 38 | + |
| 39 | + _authCode = authCode; |
| 40 | + _proxy = proxy; |
| 41 | + |
| 42 | + String message = MessageFormat.format("Created instance with " |
| 43 | + + "connectionTimeout {0}, readTimeout {1}, maxRetryTimes {2}, SSL Version {3}", |
| 44 | + _connectionTimeout, _readTimeout, _maxRetryTimes, _sslVer); |
| 45 | + LOG.info(message); |
| 46 | + |
| 47 | + if (null != _proxy && _proxy.isAuthenticationNeeded()) { |
| 48 | + Authenticator.setDefault(new NativeHttpClient.SimpleProxyAuthenticator( |
| 49 | + _proxy.getUsername(), _proxy.getPassword())); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + @Override |
| 54 | + public ResponseWrapper sendGet(String url) throws APIConnectionException, APIRequestException { |
| 55 | + return sendGet(url, null); |
| 56 | + } |
| 57 | + |
| 58 | + public ResponseWrapper sendGet(String url, String content) throws APIConnectionException, APIRequestException { |
| 59 | + ResponseWrapper wrapper = new ResponseWrapper(); |
| 60 | + LOG.debug("Send request - Get" + " " + url); |
| 61 | + if (null != content) { |
| 62 | + LOG.debug("Request Content - " + content); |
| 63 | + } |
| 64 | + |
| 65 | + try { |
| 66 | + Request request = new Request.Builder().url(url) |
| 67 | + .header("User-Agent", JPUSH_USER_AGENT) |
| 68 | + .addHeader("Accept-Charset", CHARSET) |
| 69 | + .addHeader("Charset", CHARSET) |
| 70 | + .addHeader("Connection", "Keep-Alive") |
| 71 | + .addHeader("Authorization", _authCode) |
| 72 | + .addHeader("Content-Type", CONTENT_TYPE_JSON) |
| 73 | + .build(); |
| 74 | + if (null != content) { |
| 75 | + byte[] data = content.getBytes(CHARSET); |
| 76 | + request.newBuilder().header("Content-Length", String.valueOf(data.length)); |
| 77 | + } |
| 78 | + handleResponse(wrapper, request); |
| 79 | + } catch (UnsupportedEncodingException e) { |
| 80 | + e.printStackTrace(); |
| 81 | + } catch (IOException e) { |
| 82 | + e.printStackTrace(); |
| 83 | + } |
| 84 | + return wrapper; |
| 85 | + } |
| 86 | + |
| 87 | + public void handleResponse(ResponseWrapper wrapper, Request request) throws IOException { |
| 88 | + OkHttpClient client = new OkHttpClient.Builder() |
| 89 | + .connectTimeout(_connectionTimeout, TimeUnit.MILLISECONDS) |
| 90 | + .readTimeout(_readTimeout, TimeUnit.MILLISECONDS) |
| 91 | + .build(); |
| 92 | + okhttp3.Response response = client.newCall(request).execute(); |
| 93 | + if (response.isSuccessful()) { |
| 94 | + wrapper.responseCode = 200; |
| 95 | + wrapper.responseContent = response.body().string(); |
| 96 | + LOG.debug("Succeed to get response OK - response body: " + wrapper.responseContent); |
| 97 | +// InputStream in = response.body().byteStream(); |
| 98 | +// StringBuffer sb = new StringBuffer(); |
| 99 | +// if (null != in) { |
| 100 | +// InputStreamReader reader = new InputStreamReader(in, CHARSET); |
| 101 | +// char[] buff = new char[1024]; |
| 102 | +// int len; |
| 103 | +// while ((len = reader.read(buff)) > 0) { |
| 104 | +// sb.append(buff, 0, len); |
| 105 | +// } |
| 106 | +// } |
| 107 | + } else { |
| 108 | + int status = response.code(); |
| 109 | + wrapper.responseCode = status; |
| 110 | + wrapper.responseContent = response.body().string(); |
| 111 | + if (status >= 300 && status < 400) { |
| 112 | + LOG.warn("Normal response but unexpected - responseCode:" + status + ", responseContent:" + wrapper.responseContent); |
| 113 | + |
| 114 | + } else { |
| 115 | + LOG.warn("Got error response - responseCode:" + status + ", responseContent:" + wrapper.responseContent); |
| 116 | + |
| 117 | + switch (status) { |
| 118 | + case 400: |
| 119 | + LOG.error("Your request params is invalid. Please check them according to error message."); |
| 120 | + wrapper.setErrorObject(); |
| 121 | + break; |
| 122 | + case 401: |
| 123 | + LOG.error("Authentication failed! Please check authentication params according to docs."); |
| 124 | + wrapper.setErrorObject(); |
| 125 | + break; |
| 126 | + case 403: |
| 127 | + LOG.error("Request is forbidden! Maybe your appkey is listed in blacklist or your params is invalid."); |
| 128 | + wrapper.setErrorObject(); |
| 129 | + break; |
| 130 | + case 404: |
| 131 | + LOG.error("Request page is not found! Maybe your params is invalid."); |
| 132 | + wrapper.setErrorObject(); |
| 133 | + break; |
| 134 | + case 410: |
| 135 | + LOG.error("Request resource is no longer in service. Please according to notice on official website."); |
| 136 | + wrapper.setErrorObject(); |
| 137 | + case 429: |
| 138 | + LOG.error("Too many requests! Please review your appkey's request quota."); |
| 139 | + wrapper.setErrorObject(); |
| 140 | + break; |
| 141 | + case 500: |
| 142 | + case 502: |
| 143 | + case 503: |
| 144 | + case 504: |
| 145 | + LOG.error("Seems encountered server error. Maybe JPush is in maintenance? Please retry later."); |
| 146 | + break; |
| 147 | + default: |
| 148 | + LOG.error("Unexpected response."); |
| 149 | + } |
| 150 | + } |
| 151 | + LOG.warn("Got error response - response: " + response.body().string()); |
| 152 | + wrapper.setErrorObject(); |
| 153 | + } |
| 154 | + } |
| 155 | + |
| 156 | + @Override |
| 157 | + public ResponseWrapper sendDelete(String url) throws APIConnectionException, APIRequestException { |
| 158 | + ResponseWrapper wrapper = new ResponseWrapper(); |
| 159 | + LOG.debug("Send request - Delete url:" + " " + url); |
| 160 | + Request request; |
| 161 | + try { |
| 162 | + request = new Request.Builder().url(url) |
| 163 | + .header("User-Agent", JPUSH_USER_AGENT) |
| 164 | + .addHeader("Accept-Charset", CHARSET) |
| 165 | + .addHeader("Charset", CHARSET) |
| 166 | + .addHeader("Connection", "Keep-Alive") |
| 167 | + .addHeader("Authorization", _authCode) |
| 168 | + .addHeader("Content-Type", CONTENT_TYPE_JSON) |
| 169 | + .delete().build(); |
| 170 | + handleResponse(wrapper, request); |
| 171 | + } catch (UnsupportedEncodingException e) { |
| 172 | + e.printStackTrace(); |
| 173 | + } catch (IOException e) { |
| 174 | + e.printStackTrace(); |
| 175 | + } |
| 176 | + return wrapper; |
| 177 | + } |
| 178 | + |
| 179 | + @Override |
| 180 | + public ResponseWrapper sendPost(String url, String content) throws APIConnectionException, APIRequestException { |
| 181 | + LOG.debug("Send request - Post url:" + " " + url + " content: " + content); |
| 182 | + ResponseWrapper wrapper = new ResponseWrapper(); |
| 183 | + try { |
| 184 | + RequestBody body = RequestBody.create(JSON, content); |
| 185 | + Request request = new Request.Builder().url(url) |
| 186 | + .header("User-Agent", JPUSH_USER_AGENT) |
| 187 | + .addHeader("Accept-Charset", CHARSET) |
| 188 | + .addHeader("Charset", CHARSET) |
| 189 | + .addHeader("Connection", "Keep-Alive") |
| 190 | + .addHeader("Authorization", _authCode) |
| 191 | + .addHeader("Content-Type", CONTENT_TYPE_JSON) |
| 192 | + .post(body).build(); |
| 193 | + handleResponse(wrapper, request); |
| 194 | + } catch (UnsupportedEncodingException e) { |
| 195 | + e.printStackTrace(); |
| 196 | + } catch (IOException e) { |
| 197 | + e.printStackTrace(); |
| 198 | + } |
| 199 | + return wrapper; |
| 200 | + } |
| 201 | + |
| 202 | + @Override |
| 203 | + public ResponseWrapper sendPut(String url, String content) throws APIConnectionException, APIRequestException { |
| 204 | + LOG.debug("Send request - Put url:" + " " + url + " content: " + content); |
| 205 | + ResponseWrapper wrapper = new ResponseWrapper(); |
| 206 | + try { |
| 207 | + RequestBody body = RequestBody.create(JSON, content); |
| 208 | + Request request = new Request.Builder().url(url) |
| 209 | + .header("User-Agent", JPUSH_USER_AGENT) |
| 210 | + .addHeader("Accept-Charset", CHARSET) |
| 211 | + .addHeader("Charset", CHARSET) |
| 212 | + .addHeader("Connection", "Keep-Alive") |
| 213 | + .addHeader("Authorization", _authCode) |
| 214 | + .addHeader("Content-Type", CONTENT_TYPE_JSON) |
| 215 | + .put(body).build(); |
| 216 | + handleResponse(wrapper, request); |
| 217 | + } catch (UnsupportedEncodingException e) { |
| 218 | + e.printStackTrace(); |
| 219 | + } catch (IOException e) { |
| 220 | + e.printStackTrace(); |
| 221 | + } |
| 222 | + return wrapper; |
| 223 | + } |
| 224 | +} |
0 commit comments