List of usage examples for com.squareup.okhttp Request.Builder Request.Builder
Request.Builder
From source file:com.frostwire.util.http.OKHTTPClient.java
License:Open Source License
private Request.Builder prepareRequestBuilder(OkHttpClient okHttpClient, String url, int timeout, String userAgent, String referrer, String cookie) { okHttpClient.setConnectTimeout(timeout, TimeUnit.MILLISECONDS); okHttpClient.setReadTimeout(timeout, TimeUnit.MILLISECONDS); okHttpClient.setWriteTimeout(timeout, TimeUnit.MILLISECONDS); okHttpClient.interceptors().clear(); Request.Builder builder = new Request.Builder(); builder.url(url);/*from w w w .jav a2 s . c o m*/ if (!StringUtils.isNullOrEmpty(userAgent)) { builder.header("User-Agent", userAgent); } if (!StringUtils.isNullOrEmpty(referrer)) { builder.header("Referer", referrer); // [sic - typo in HTTP protocol] } if (!StringUtils.isNullOrEmpty(cookie)) { builder.header("Cookie", cookie); } return builder; }
From source file:com.github.automately.sdk.Automately.java
License:Mozilla Public License
public static JsonObject getAutomatelyCloudPlan() { try {/*from w w w . j a va 2s. c o m*/ JsonObject requestData = new JsonObject(); requestData.putString("username", getApiUsername()); requestData.putString("apiKey", getApiKey()); Request request = new Request.Builder() .url(USER_API_ENDPOINT + "/getPlan").post(RequestBody .create(MediaType.parse("application/json"), requestData.toString().getBytes())) .build(); Response response = httpClient.newCall(request).execute(); if (response != null) { String responseEntity = response.body().string(); try { return new JsonObject(responseEntity); } catch (DecodeException ignored) { getFormattedError("Decode Exception", "There was an issue decoding the response."); } } } catch (IOException ignored) { } return null; }
From source file:com.github.automately.sdk.Automately.java
License:Mozilla Public License
public static JsonObject getAutomatelyCloudPlans() { try {/*w ww . j av a 2 s .c o m*/ Request request = new Request.Builder().url(USER_API_ENDPOINT + "/getPlans").get().build(); Response response = httpClient.newCall(request).execute(); if (response != null) { String responseEntity = response.body().string(); try { return new JsonObject(responseEntity); } catch (DecodeException ignored) { getFormattedError("Decode Exception", "There was an issue decoding the response."); } } } catch (IOException ignored) { } return null; }
From source file:com.github.automately.sdk.Automately.java
License:Mozilla Public License
public static JsonObject setAutomatelyCloudPlan(String planId) { try {/* ww w . ja va 2 s . c o m*/ JsonObject requestData = new JsonObject(); requestData.putString("planId", planId); requestData.putString("username", getApiUsername()); requestData.putString("apiKey", getApiKey()); Request request = new Request.Builder() .url(USER_API_ENDPOINT + "/changePlan").post(RequestBody .create(MediaType.parse("application/json"), requestData.toString().getBytes())) .build(); Response response = httpClient.newCall(request).execute(); if (response != null) { String responseEntity = response.body().string(); try { return new JsonObject(responseEntity); } catch (DecodeException ignored) { getFormattedError("Decode Exception", "There was an issue decoding the response."); } } } catch (IOException ignored) { } return null; }
From source file:com.github.automately.sdk.Automately.java
License:Mozilla Public License
public static JsonObject registerModule(JsonObject manifest) { try {// w ww. j av a 2 s .c o m JsonObject requestData = new JsonObject(); // The module register requires authentication requestData.putObject("manifest", manifest); requestData.putString("username", getApiUsername()); requestData.putString("apiKey", getApiKey()); Request request = new Request.Builder().url(REGISTRY_ENDPOINT + "/submit").post( RequestBody.create(MediaType.parse("application/json"), requestData.toString().getBytes())) .build(); Response response = httpClient.newCall(request).execute(); if (response != null) { String responseEntity = response.body().string(); try { checkAuthorized(responseEntity); return new JsonObject(responseEntity); } catch (DecodeException ignored) { getFormattedError("Decode Exception", "There was an issue decoding the response."); } } } catch (IOException ignored) { } return null; }
From source file:com.github.automately.sdk.Automately.java
License:Mozilla Public License
public static JsonObject findModule(String moduleName) { try {// w w w .j av a 2s . co m // TODO Include credentials to allow for the searching of private user modules Request request = new Request.Builder().url(REGISTRY_ENDPOINT + "/retrieve?name=" + moduleName).get() .build(); Response response = httpClient.newCall(request).execute(); if (response != null) { String responseEntity = response.body().string(); try { checkAuthorized(responseEntity); return new JsonObject(responseEntity); } catch (DecodeException ignored) { getFormattedError("Decode Exception", "There was an issue decoding the response."); } } } catch (IOException ignored) { } return null; }
From source file:com.github.drrb.surefiresplitter.go.GoServer.java
License:Open Source License
private ResponseBody get(String url) throws CommunicationError { Request.Builder requestBuilder = new Request.Builder().get().url(url); if (username != null && password != null) { requestBuilder.addHeader("Authorization", Credentials.basic(username, password)); }//from w w w . jav a2 s . c om Response response = execute(requestBuilder.build()); if (response.isSuccessful()) { return response.body(); } else { String errorMessage = String.format("Bad status code when requesting: %s (%d: %s)", url, response.code(), response.message()); try (ResponseBody responseBody = response.body()) { errorMessage += ("\n" + responseBody.string()); } catch (IOException e) { errorMessage += ". Tried to read the response body for a helpful message, but couldn't (Error was '" + e.getMessage() + "')."; } throw new CommunicationError(errorMessage); } }
From source file:com.mycelium.lt.api.LtApiClient.java
License:Apache License
private Response getConnectionAndSendRequest(LtRequest request, int timeout) { int originalConnectionIndex = _serverEndpoints.getCurrentEndpointIndex(); // Figure what our current endpoint is. On errors we fail over until we // are back at the initial endpoint HttpEndpoint initialEndpoint = getEndpoint(); while (true) { HttpEndpoint serverEndpoint = _serverEndpoints.getCurrentEndpoint(); try {//from w w w. j av a 2 s. c o m OkHttpClient client = serverEndpoint.getClient(); _logger.logInfo("LT connecting to " + serverEndpoint.getBaseUrl() + " (" + _serverEndpoints.getCurrentEndpointIndex() + ")"); // configure TimeOuts client.setConnectTimeout(timeout, TimeUnit.MILLISECONDS); client.setReadTimeout(timeout, TimeUnit.MILLISECONDS); client.setWriteTimeout(timeout, TimeUnit.MILLISECONDS); Stopwatch callDuration = Stopwatch.createStarted(); // build request final String toSend = getPostBody(request); Request rq = new Request.Builder() .post(RequestBody.create(MediaType.parse("application/json"), toSend)) .url(serverEndpoint.getUri(request.toString()).toString()).build(); // execute request Response response = client.newCall(rq).execute(); callDuration.stop(); _logger.logInfo(String.format("LtApi %s finished (%dms)", request.toString(), callDuration.elapsed(TimeUnit.MILLISECONDS))); // Check for status code 2XX if (response.isSuccessful()) { if (serverEndpoint instanceof FeedbackEndpoint) { ((FeedbackEndpoint) serverEndpoint).onSuccess(); } return response; } else { // If the status code is not 200 we cycle to the next server logError(String.format("Local Trader server request for class %s returned HTTP status code %d", request.getClass().toString(), response.code())); } } catch (IOException e) { logError("getConnectionAndSendRequest failed IO exception."); if (serverEndpoint instanceof FeedbackEndpoint) { _logger.logInfo("Resetting tor"); ((FeedbackEndpoint) serverEndpoint).onError(); } } // We had an IO exception or a bad status, fail over and try again _serverEndpoints.switchToNextEndpoint(); // Check if we are back at the initial endpoint, in which case we have // to give up if (_serverEndpoints.getCurrentEndpointIndex() == originalConnectionIndex) { // We have tried all URLs return null; } } }
From source file:com.mycelium.wapi.api.WapiClient.java
License:Apache License
/** * Attempt to connect and send to a URL in our list of URLS, if it fails try * the next until we have cycled through all URLs. timeout. *//*ww w. j a v a 2 s .c om*/ private Response getConnectionAndSendRequestWithTimeout(Object request, String function, int timeout) { int originalConnectionIndex = _serverEndpoints.getCurrentEndpointIndex(); while (true) { // currently active server-endpoint HttpEndpoint serverEndpoint = _serverEndpoints.getCurrentEndpoint(); try { OkHttpClient client = serverEndpoint.getClient(); _logger.logInfo("Connecting to " + serverEndpoint.getBaseUrl() + " (" + _serverEndpoints.getCurrentEndpointIndex() + ")"); // configure TimeOuts client.setConnectTimeout(timeout, TimeUnit.MILLISECONDS); client.setReadTimeout(timeout, TimeUnit.MILLISECONDS); client.setWriteTimeout(timeout, TimeUnit.MILLISECONDS); Stopwatch callDuration = Stopwatch.createStarted(); // build request final String toSend = getPostBody(request); Request rq = new Request.Builder().addHeader(MYCELIUM_VERSION_HEADER, versionCode) .post(RequestBody.create(MediaType.parse("application/json"), toSend)) .url(serverEndpoint.getUri(WapiConst.WAPI_BASE_PATH, function).toString()).build(); // execute request Response response = client.newCall(rq).execute(); callDuration.stop(); _logger.logInfo(String.format("Wapi %s finished (%dms)", function, callDuration.elapsed(TimeUnit.MILLISECONDS))); // Check for status code 2XX if (response.isSuccessful()) { if (serverEndpoint instanceof FeedbackEndpoint) { ((FeedbackEndpoint) serverEndpoint).onSuccess(); } return response; } else { // If the status code is not 200 we cycle to the next server logError(String.format("Http call to %s failed with %d %s", function, response.code(), response.message())); // throw... } } catch (IOException e) { logError("IOException when sending request " + function, e); if (serverEndpoint instanceof FeedbackEndpoint) { _logger.logInfo("Resetting tor"); ((FeedbackEndpoint) serverEndpoint).onError(); } } // Try the next server _serverEndpoints.switchToNextEndpoint(); if (_serverEndpoints.getCurrentEndpointIndex() == originalConnectionIndex) { // We have tried all URLs return null; } } }
From source file:com.navercorp.pinpoint.plugin.okhttp.OkHttpClientBackwardCompatibilityIT.java
License:Apache License
@Test public void execute() throws Exception { Request request = new Request.Builder().url("http://google.com").build(); OkHttpClient client = new OkHttpClient(); Response response = client.newCall(request).execute(); PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance(); verifier.printCache();/* w w w. j ava 2 s .co m*/ Method callMethod = Call.class.getDeclaredMethod("execute"); verifier.verifyTrace(Expectations.event("OK_HTTP_CLIENT_INTERNAL", callMethod)); }