public ServerInfoJson getServerInfo(HttpUrl serverUrl, String serverID, String id) throws IOException { // set timeout to 30 seconds OkHttpClient client = defaultClient .newBuilder() .connectTimeout(30, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .build(); JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("version", 1); jsonObject.addProperty("command", "get_server_info"); jsonObject.addProperty("stop_when_error", "false"); jsonObject.addProperty("stop_when_success", "false"); jsonObject.addProperty("id", id); jsonObject.addProperty("serverID", serverID); RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), gson.toJson(jsonObject)); Request request = new Request.Builder().url(serverUrl).post(requestBody).build(); Response response = client.newCall(request).execute(); InputStream in = response.body().byteStream(); JsonReader reader = null; ServerInfoJson serverInfoJson = null; try { reader = new JsonReader(new InputStreamReader(in, "UTF-8")); serverInfoJson = gson.fromJson(reader, ServerInfoJson.class); } finally { if (reader != null) { reader.close(); } } if (serverInfoJson != null) { if (serverInfoJson.server != null) { // server info found! return serverInfoJson; } else if (serverInfoJson.sites != null && !serverInfoJson.sites.isEmpty()) { String site = serverInfoJson.sites.get(0); return getServerInfo( new HttpUrl.Builder().scheme("http").host(site).addPathSegment("Serv.php").build(), serverID, id); } } throw new IOException("No server info found!"); }
private String authorize() { try { OkHttpClient.Builder builder = client.newBuilder(); builder.interceptors().remove(this); OkHttpClient clone = builder.build(); String credential = Credentials.basic(config.getUsername(), new String(config.getPassword())); URL url = new URL(URLUtils.join(config.getMasterUrl(), AUTHORIZE_PATH)); Response response = clone .newCall( new Request.Builder().get().url(url).header(AUTHORIZATION, credential).build()) .execute(); response.body().close(); response = response.priorResponse() != null ? response.priorResponse() : response; response = response.networkResponse() != null ? response.networkResponse() : response; String token = response.header(LOCATION); if (token == null || token.isEmpty()) { throw new KubernetesClientException( "Unexpected response (" + response.code() + " " + response.message() + "), to the authorization request. Missing header:[" + LOCATION + "]!"); } token = token.substring(token.indexOf(BEFORE_TOKEN) + BEFORE_TOKEN.length()); token = token.substring(0, token.indexOf(AFTER_TOKEN)); return token; } catch (Exception e) { throw KubernetesClientException.launderThrowable(e); } }
private static OkHttpClient client() { return client .newBuilder() .connectTimeout(250, TimeUnit.MILLISECONDS) .readTimeout(250, TimeUnit.MILLISECONDS) .build(); }
@Override public byte[] download(String url, String accepts) { HttpUrl httpUrl = HttpUrl.parse(url); if (httpUrl == null) { App.log.log(Level.SEVERE, "Invalid external resource URL", url); return null; } String host = httpUrl.host(); if (host == null) { App.log.log(Level.SEVERE, "External resource URL doesn't specify a host name", url); return null; } OkHttpClient resourceClient = HttpClient.create(); // authenticate only against a certain host, and only upon request resourceClient = HttpClient.addAuthentication( resourceClient, baseUrl.host(), settings.username(), settings.password()); // allow redirects resourceClient = resourceClient.newBuilder().followRedirects(true).build(); try { Response response = resourceClient.newCall(new Request.Builder().get().url(httpUrl).build()).execute(); ResponseBody body = response.body(); if (body != null) { @Cleanup InputStream stream = body.byteStream(); if (response.isSuccessful() && stream != null) { return IOUtils.toByteArray(stream); } else App.log.severe("Couldn't download external resource"); } } catch (IOException e) { App.log.log(Level.SEVERE, "Couldn't download external resource", e); } return null; }
public ServerInfoJson requestTunnel(ServerInfoJson infoJson, String serverID, String id) throws IOException { if (infoJson == null || infoJson.env == null || Util.isEmpty(infoJson.env.control_host)) { return null; } // set timeout to 30 seconds OkHttpClient client = defaultClient .newBuilder() .connectTimeout(30, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .build(); final String server = infoJson.env.control_host; JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("command", "request_tunnel"); jsonObject.addProperty("version", 1); jsonObject.addProperty("serverID", serverID); jsonObject.addProperty("id", id); RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), gson.toJson(jsonObject)); Request request = new Request.Builder() .url(HttpUrl.parse("http://" + server + "/Serv.php")) .post(requestBody) .build(); Response response = client.newCall(request).execute(); JsonReader reader = null; try { InputStream in = response.body().byteStream(); reader = new JsonReader(new InputStreamReader(in, "UTF-8")); return gson.fromJson(reader, ServerInfoJson.class); } finally { if (reader != null) { reader.close(); } } }
/** * 双向认证 * * @param certificates 服务端证书 * @param bksFile 客户端签名 * @param password 签名密码 */ @SuppressLint("TrulyRandom") public void setCertificates(InputStream[] certificates, InputStream bksFile, String password) { throwException(); try { TrustManager[] trustManagers = prepareTrustManager(certificates); KeyManager[] keyManagers = prepareKeyManager(bksFile, password); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init( keyManagers, new TrustManager[] {new CustomeTrustManager(chooseTrustManager(trustManagers))}, new SecureRandom()); mOkHttpClient.newBuilder().sslSocketFactory(sslContext.getSocketFactory()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } }
/** * 包装OkHttpClient,用于下载文件的回调 * * @param client 待包装的OkHttpClient * @param progressListener 进度回调接口 * @return 包装后的OkHttpClient,使用clone方法返回 */ public static OkHttpClient addProgressResponseListener( OkHttpClient client, final ProgressListener progressListener) { // 克隆 OkHttpClient clone = client.newBuilder().build(); // 增加拦截器 clone .networkInterceptors() .add( new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { // 拦截 Response originalResponse = chain.proceed(chain.request()); // 包装响应体并返回 return originalResponse .newBuilder() .body(new ProgressResponseBody(originalResponse.body(), progressListener)) .build(); } }); return clone; }
private HttpUrl pingTunnel(ServiceJson serviceJson) { if (serviceJson == null || Util.isEmpty(serviceJson.relay_ip) || serviceJson.relay_port == 0) { return null; } // set timeout to 10 seconds OkHttpClient client = defaultClient .newBuilder() .connectTimeout(5, TimeUnit.SECONDS) .readTimeout(5, TimeUnit.SECONDS) .build(); String relayIp = serviceJson.relay_ip; int relayPort = serviceJson.relay_port; // tunnel address ExecutorService executor = Executors.newFixedThreadPool(10); CompletionService<String> service = new ExecutorCompletionService<>(executor); service.submit(createPingTask(client, relayIp, relayPort)); try { Future<String> future = service.take(); if (future != null) { String host = future.get(); if (!Util.isEmpty(host)) { return requestUrl.newBuilder().host(host).port(relayPort).build(); } } } catch (InterruptedException | ExecutionException ignored) { } // shutdown executors executor.shutdownNow(); return null; }
public static OkHttpClient okHttpClientWithIdlingResources(OkHttpClient client) { return client .newBuilder() .addInterceptor(OkClientFactory.provideIdlingResourcesInterceptor()) .build(); }
public static void setRetryOnConnectionFailure(boolean retryOnConnectionFailure) { mOkHttpClient = mOkHttpClient.newBuilder().retryOnConnectionFailure(retryOnConnectionFailure).build(); }
public static void setConnectTimeout(int second) { mOkHttpClient = mOkHttpClient.newBuilder().connectTimeout(second, TimeUnit.SECONDS).build(); }
/** * Clones the okBuilder given in parameter, adds the auth interceptors and uses it to configure * the Retrofit * * @param okClient An instance of OK HTTP client */ public void configureFromOkclient(OkHttpClient okClient) { this.okBuilder = okClient.newBuilder(); addAuthsToOkBuilder(this.okBuilder); }
public HttpUrl pingDSM(ServerInfoJson infoJson) { // set timeout to 5 seconds final OkHttpClient client = defaultClient .newBuilder() .connectTimeout(5, TimeUnit.SECONDS) .readTimeout(5, TimeUnit.SECONDS) .build(); ServerJson serverJson = infoJson.server; if (serverJson == null) { throw new IllegalArgumentException("serverJson == null"); } ServiceJson serviceJson = infoJson.service; if (serviceJson == null) { throw new IllegalArgumentException("serviceJson == null"); } int port = serviceJson.port; int externalPort = serviceJson.ext_port; // internal address(192.168.x.x/10.x.x.x) ExecutorService executor = Executors.newFixedThreadPool(10); CompletionService<String> internalService = new ExecutorCompletionService<>(executor); List<InterfaceJson> ifaces = serverJson._interface; AtomicInteger internalCount = new AtomicInteger(0); if (ifaces != null) { for (final InterfaceJson iface : ifaces) { internalService.submit(createPingTask(client, iface.ip, port)); internalCount.incrementAndGet(); if (iface.ipv6 != null) { for (Ipv6Json ipv6 : iface.ipv6) { String ipv6Address = "[" + ipv6.address + "]"; internalService.submit(createPingTask(client, ipv6Address, port)); internalCount.incrementAndGet(); } } } } // host address(ddns/fqdn) ExecutorCompletionService<String> hostService = new ExecutorCompletionService<>(executor); AtomicInteger hostCount = new AtomicInteger(0); // ddns if (!Util.isEmpty(serverJson.ddns) && !serverJson.ddns.equals("NULL")) { hostService.submit(createPingTask(client, serverJson.ddns, port)); hostCount.incrementAndGet(); } // fqdn if (!Util.isEmpty(serverJson.fqdn) && !serverJson.fqdn.equals("NULL")) { hostService.submit(createPingTask(client, serverJson.fqdn, port)); hostCount.incrementAndGet(); } // external address(public ip address) ExecutorCompletionService<String> externalService = new ExecutorCompletionService<>(executor); AtomicInteger externalCount = new AtomicInteger(0); if (serverJson.external != null) { String ip = serverJson.external.ip; if (!Util.isEmpty(ip)) { externalService.submit( createPingTask(client, ip, (externalPort != 0) ? externalPort : port)); externalCount.incrementAndGet(); } String ipv6 = serverJson.external.ipv6; if (!Util.isEmpty(ipv6) && !ipv6.equals("::")) { externalService.submit( createPingTask(client, "[" + ipv6 + "]", (externalPort != 0) ? externalPort : port)); externalCount.incrementAndGet(); } } while (internalCount.getAndDecrement() > 0) { try { Future<String> future = internalService.take(); if (future != null) { String host = future.get(); if (!Util.isEmpty(host)) { return requestUrl.newBuilder().host(host).port(port).build(); } } } catch (InterruptedException | ExecutionException ignored) { } } while (hostCount.getAndDecrement() > 0) { try { Future<String> future = hostService.take(); if (future != null) { String host = future.get(); if (!Util.isEmpty(host)) { return requestUrl.newBuilder().host(host).port(port).build(); } } } catch (InterruptedException | ExecutionException ignored) { } } while (externalCount.getAndDecrement() > 0) { try { Future<String> future = externalService.take(); if (future != null) { String host = future.get(); if (!Util.isEmpty(host)) { return requestUrl.newBuilder().host(host).port(port).build(); } } } catch (InterruptedException | ExecutionException ignored) { // ignored.printStackTrace(); } } // shutdown executors executor.shutdownNow(); return null; }