List of usage examples for com.squareup.okhttp Response toString
@Override
public String toString()
From source file:com.commonsware.android.okhttp.LoadThread.java
License:Apache License
@Override public void run() { try {//from w ww .j a v a 2 s. com OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(SO_URL).build(); Response response = client.newCall(request).execute(); if (response.isSuccessful()) { Reader in = response.body().charStream(); BufferedReader reader = new BufferedReader(in); SOQuestions questions = new Gson().fromJson(reader, SOQuestions.class); reader.close(); EventBus.getDefault().post(new QuestionsLoadedEvent(questions)); } else { Log.e(getClass().getSimpleName(), response.toString()); } } catch (Exception e) { Log.e(getClass().getSimpleName(), "Exception parsing JSON", e); } }
From source file:com.piusvelte.okoauth.Helper.java
License:Apache License
@NonNull public void getTokenSecret(@NonNull OkHttpClient client) { Request request = new RequestTokenRequestBuilder(mConsumerKey, mConsumerSecret, mCallbackUrl) .url(mTokenRequestUrl).build(); Response response; try {/*from ww w . j av a 2s. c o m*/ response = client.newCall(request).execute(); if (response.isSuccessful() && response.body() != null) { String content = response.body().string(); if (!TextUtils.isEmpty(content)) { String[] keyValuePairs = content.split("&"); if (keyValuePairs.length > 1) { for (String keyValuePair : keyValuePairs) { String[] keyValuePairParts = keyValuePair.split("="); if (keyValuePairParts.length > 1) { String key = keyValuePairParts[0]; String value = keyValuePairParts[1]; if (RequestBuilder.OAuthParameter.oauth_token.name().equals(key)) { mToken = value; } else if ("oauth_token_secret".equals(key)) { mTokenSecret = value; } else if ("oauth_callback_confirmed".equals(key)) { mIsOAuth10a = Boolean.TRUE.toString().equals(value); } } } } } } else { if (BuildConfig.DEBUG) { Log.e(TAG, "unsuccessful getting token" + response.toString()); } } } catch (IOException e) { if (BuildConfig.DEBUG) { Log.e(TAG, "failed getting token", e); } } }
From source file:com.shipdream.lib.android.mvc.samples.note.service.http.internal.WeatherServiceImpl.java
License:Apache License
@Override public WeatherListResponse getWeathers(List<Integer> ids) throws IOException { String idsStr = ""; for (Integer id : ids) { if (!idsStr.isEmpty()) { idsStr += ", "; }/*from w w w .j av a 2s . com*/ idsStr += String.valueOf(id); } String url = String.format("http://api.openweathermap.org/data/2.5/group?id=%s&units=metric", URLEncoder.encode(idsStr, "UTF-8")); Request request = new Request.Builder().url(url).get().build(); Response resp = httpClient.newCall(request).execute(); String responseStr = resp.toString(); return gson.fromJson(responseStr, WeatherListResponse.class); }
From source file:com.xebialabs.xlt.ci.server.XLTestServerImpl.java
License:Open Source License
@Override public void checkConnection() { try {//from w ww. j a v a2s .c o m LOG.info("Checking connection to {}", serverUrl); Request request = createRequestFor(API_CONNECTION_CHECK); Response response = client.newCall(request).execute(); switch (response.code()) { case 200: return; case 401: throw new AuthenticationException(String.format( "User '%s' and the supplied password are unable to log in", credentials.getUsername())); case 402: throw new PaymentRequiredException("The XL TestView server does not have a valid license"); case 404: throw new ConnectionException("URL is invalid or server is not running"); default: throw new IllegalStateException("Unknown error. Status code: " + response.code() + ". Response message: " + response.toString()); } } catch (IOException e) { throw new RuntimeException(e); } }
From source file:com.xebialabs.xlt.ci.server.XLTestServerImpl.java
License:Open Source License
@Override public void uploadTestRun(String testSpecificationId, FilePath workspace, String includes, String excludes, Map<String, Object> metadata, PrintStream logger) throws IOException, InterruptedException { if (testSpecificationId == null || testSpecificationId.isEmpty()) { throw new IllegalArgumentException( "No test specification id specified. Does the test specification still exist in XL TestView?"); }/*w w w.ja v a 2 s . c o m*/ try { logInfo(logger, format("Collecting files from '%s' using include pattern: '%s' and exclude pattern '%s'", workspace.getRemote(), includes, excludes)); DirScanner scanner = new DirScanner.Glob(includes, excludes); ObjectMapper objectMapper = new ObjectMapper(); RequestBody body = new MultipartBuilder().type(MultipartBuilder.MIXED) .addPart(RequestBody.create(MediaType.parse(APPLICATION_JSON_UTF_8), objectMapper.writeValueAsString(metadata))) .addPart(new ZipRequestBody(workspace, scanner, logger)).build(); Request request = new Request.Builder() .url(createSensibleURL(API_IMPORT + "/" + testSpecificationId, serverUrl)) .header("User-Agent", getUserAgent()).header("Accept", APPLICATION_JSON_UTF_8) .header("Authorization", createCredentials()).header("Transfer-Encoding", "chunked").post(body) .build(); Response response = client.newCall(request).execute(); ObjectMapper mapper = createMapper(); ImportError importError; switch (response.code()) { case 200: logInfo(logger, "Sent data successfully"); return; case 304: logWarn(logger, "No new results were detected. Nothing was imported."); throw new IllegalStateException("No new results were detected. Nothing was imported."); case 400: importError = mapper.readValue(response.body().byteStream(), ImportError.class); throw new IllegalStateException(importError.getMessage()); case 401: throw new AuthenticationException(String.format( "User '%s' and the supplied password are unable to log in", credentials.getUsername())); case 402: throw new PaymentRequiredException("The XL TestView server does not have a valid license"); case 404: throw new ConnectionException("Cannot find test specification '" + testSpecificationId + ". Please check if the XL TestView server is " + "running and the test specification exists."); case 422: logWarn(logger, "Unable to process results."); logWarn(logger, "Are you sure your include/exclude pattern provides all needed files for the test tool?"); importError = mapper.readValue(response.body().byteStream(), ImportError.class); throw new IllegalStateException(importError.getMessage()); default: throw new IllegalStateException("Unknown error. Status code: " + response.code() + ". Response message: " + response.toString()); } } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } catch (IOException e) { e.printStackTrace(); LOG.warn("I/O error uploading test run data to {} {}\n{}", serverUrl.toString(), e.toString(), e); throw new IOException( "I/O error uploading test run data to " + serverUrl.toString() + " " + e.toString(), e); } }
From source file:ooo.oxo.moments.InstaApplication.java
License:Open Source License
@Override public void onCreate() { super.onCreate(); //noinspection ConstantConditions if (TextUtils.isEmpty(BuildConfig.CLIENT_ID) || TextUtils.isEmpty(BuildConfig.CLIENT_SECRET)) { throw new IllegalStateException("Please create a \"client.properties\" in the same" + " directory of this module to specify your CLIENT_ID and CLIENT_SECRET."); }//from ww w . j a v a 2 s .com InstaSharedState.createInstance(this); httpClient = new OkHttpClient(); httpClient.interceptors().add(chain -> { Request request = chain.request(); Log.d("OkHttp", request.toString()); Response response = chain.proceed(request); Log.d("OkHttp", response.toString()); return response; }); InstaSharedState.getInstance().applyProxy(); Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .registerTypeAdapter(Date.class, new TimestampTypeAdapter()).create(); retrofit = new Retrofit.Builder().client(httpClient).addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()).baseUrl("https://api.instagram.com/") .build(); }
From source file:org.apache.hadoop.hdfs.web.oauth2.ConfRefreshTokenBasedAccessTokenProvider.java
License:Apache License
void refresh() throws IOException { try {//w w w. java 2 s . co m OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(URLConnectionFactory.DEFAULT_SOCKET_TIMEOUT, TimeUnit.MILLISECONDS); client.setReadTimeout(URLConnectionFactory.DEFAULT_SOCKET_TIMEOUT, TimeUnit.MILLISECONDS); String bodyString = Utils.postBody(GRANT_TYPE, REFRESH_TOKEN, REFRESH_TOKEN, refreshToken, CLIENT_ID, clientId); RequestBody body = RequestBody.create(URLENCODED, bodyString); Request request = new Request.Builder().url(refreshURL).post(body).build(); Response responseBody = client.newCall(request).execute(); if (responseBody.code() != HttpStatus.SC_OK) { throw new IllegalArgumentException("Received invalid http response: " + responseBody.code() + ", text = " + responseBody.toString()); } Map<?, ?> response = READER.readValue(responseBody.body().string()); String newExpiresIn = response.get(EXPIRES_IN).toString(); accessTokenTimer.setExpiresIn(newExpiresIn); accessToken = response.get(ACCESS_TOKEN).toString(); } catch (Exception e) { throw new IOException("Exception while refreshing access token", e); } }
From source file:org.apache.hadoop.hdfs.web.oauth2.CredentialBasedAccessTokenProvider.java
License:Apache License
void refresh() throws IOException { try {//from w ww . j a v a 2 s . c o m OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(URLConnectionFactory.DEFAULT_SOCKET_TIMEOUT, TimeUnit.MILLISECONDS); client.setReadTimeout(URLConnectionFactory.DEFAULT_SOCKET_TIMEOUT, TimeUnit.MILLISECONDS); String bodyString = Utils.postBody(CLIENT_SECRET, getCredential(), GRANT_TYPE, CLIENT_CREDENTIALS, CLIENT_ID, clientId); RequestBody body = RequestBody.create(URLENCODED, bodyString); Request request = new Request.Builder().url(refreshURL).post(body).build(); Response responseBody = client.newCall(request).execute(); if (responseBody.code() != HttpStatus.SC_OK) { throw new IllegalArgumentException("Received invalid http response: " + responseBody.code() + ", text = " + responseBody.toString()); } Map<?, ?> response = READER.readValue(responseBody.body().string()); String newExpiresIn = response.get(EXPIRES_IN).toString(); timer.setExpiresIn(newExpiresIn); accessToken = response.get(ACCESS_TOKEN).toString(); } catch (Exception e) { throw new IOException("Unable to obtain access token from credential", e); } }
From source file:org.fuse.hawkular.agent.monitor.cmd.FeedCommProcessor.java
License:Apache License
@Override public void onFailure(IOException e, Response response) { if (response == null) { // don't flood the log with these at the WARN level - its probably just because the server is down // and we can't reconnect - while the server is down, our reconnect logic will cause this error // to occur periodically. Our reconnect logic will log other messages. log.tracef("Feed communications had a failure - a reconnection is likely required: %s", e); } else {/*www .j ava 2 s .co m*/ log.warnFeedCommFailure(response.toString(), e); } }
From source file:org.hawkular.agent.monitor.feedcomm.FeedCommProcessor.java
License:Apache License
@Override public void onFailure(IOException e, Response response) { MsgLogger.LOG.warnFeedCommFailure((response != null) ? response.toString() : "?", e); }