List of usage examples for com.squareup.okhttp ResponseBody string
public final String string() throws IOException
From source file:com.microsoft.rest.AzureClient.java
License:Open Source License
/** * Handles an initial response from a PUT or PATCH operation response by polling * the status of the operation asynchronously, calling the user provided callback * when the operation terminates./*from www .j av a2s . co m*/ * * @param response the initial response from the PUT or PATCH operation. * @param <T> the return type of the caller. * @param resourceType the type of the resource. * @param callback the user callback to call when operation terminates. * @return the task describing the asynchronous polling. */ public <T> AsyncPollingTask<T> getPutOrPatchResultAsync(Response<ResponseBody> response, Type resourceType, ServiceCallback<T> callback) { if (response == null) { callback.failure(new ServiceException("response is null.")); return null; } int statusCode = response.code(); ResponseBody responseBody; if (response.isSuccess()) { responseBody = response.body(); } else { responseBody = response.errorBody(); } if (statusCode != 200 && statusCode != 201 && statusCode != 202) { CloudException exception = new CloudException(statusCode + " is not a valid polling status code"); exception.setResponse(response); try { if (responseBody != null) { exception.setBody((CloudError) new AzureJacksonUtils().deserialize(responseBody.string(), CloudError.class)); } } catch (Exception e) { /* ignore serialization errors on top of service errors */ } callback.failure(exception); return null; } PollingState<T> pollingState; try { pollingState = new PollingState<>(response, this.getLongRunningOperationRetryTimeout(), resourceType); } catch (IOException e) { callback.failure(e); return null; } String url = response.raw().request().urlString(); // Task runner will take it from here PutPatchPollingTask<T> task = new PutPatchPollingTask<>(pollingState, url, callback); executor.schedule(task, pollingState.getDelayInMilliseconds(), TimeUnit.MILLISECONDS); return task; }
From source file:com.microsoft.rest.AzureClient.java
License:Open Source License
/** * Handles an initial response from a POST or DELETE operation response by polling * the status of the operation until the long running operation terminates. * * @param response the initial response from the POST or DELETE operation. * @param <T> the return type of the caller * @param resourceType the type of the resource * @return the terminal response for the operation. * @throws CloudException REST exception * @throws InterruptedException interrupted exception * @throws IOException thrown by deserialization *///from w w w . j a v a 2 s .c om public <T> ServiceResponse<T> getPostOrDeleteResult(Response<ResponseBody> response, Type resourceType) throws CloudException, InterruptedException, IOException { if (response == null) { throw new CloudException("response is null."); } int statusCode = response.code(); ResponseBody responseBody; if (response.isSuccess()) { responseBody = response.body(); } else { responseBody = response.errorBody(); } if (statusCode != 200 && statusCode != 202 && statusCode != 204) { CloudException exception = new CloudException(statusCode + " is not a valid polling status code"); exception.setResponse(response); if (responseBody != null) { exception.setBody( (CloudError) new AzureJacksonUtils().deserialize(responseBody.string(), CloudError.class)); } throw exception; } PollingState<T> pollingState = new PollingState<>(response, this.getLongRunningOperationRetryTimeout(), resourceType); // Check provisioning state while (!AzureAsyncOperation.getTerminalStatuses().contains(pollingState.getStatus())) { Thread.sleep(pollingState.getDelayInMilliseconds()); if (pollingState.getAzureAsyncOperationHeaderLink() != null && !pollingState.getAzureAsyncOperationHeaderLink().isEmpty()) { updateStateFromAzureAsyncOperationHeader(pollingState); } else if (pollingState.getLocationHeaderLink() != null && !pollingState.getLocationHeaderLink().isEmpty()) { updateStateFromLocationHeaderOnPostOrDelete(pollingState); } else { CloudException exception = new CloudException("No header in response"); exception.setResponse(response); throw exception; } } // Check if operation failed if (AzureAsyncOperation.getFailedStatuses().contains(pollingState.getStatus())) { throw new CloudException("Async operation failed"); } return new ServiceResponse<>(pollingState.getResource(), pollingState.getResponse()); }
From source file:com.microsoft.rest.AzureClient.java
License:Open Source License
/** * Handles an initial response from a POST or DELETE operation response by polling * the status of the operation asynchronously, calling the user provided callback * when the operation terminates.//from w w w. j a v a 2 s.c o m * * @param response the initial response from the POST or DELETE operation. * @param <T> the return type of the caller. * @param resourceType the type of the resource. * @param callback the user callback to call when operation terminates. * @return the task describing the asynchronous polling. */ public <T> AsyncPollingTask<T> getPostOrDeleteResultAsync(Response<ResponseBody> response, Type resourceType, ServiceCallback<T> callback) { if (response == null) { callback.failure(new ServiceException("response is null.")); return null; } int statusCode = response.code(); ResponseBody responseBody; if (response.isSuccess()) { responseBody = response.body(); } else { responseBody = response.errorBody(); } if (statusCode != 200 && statusCode != 201 && statusCode != 202) { CloudException exception = new CloudException(statusCode + " is not a valid polling status code"); exception.setResponse(response); try { if (responseBody != null) { exception.setBody((CloudError) new AzureJacksonUtils().deserialize(responseBody.string(), CloudError.class)); } } catch (Exception e) { /* ignore serialization errors on top of service errors */ } callback.failure(exception); return null; } PollingState<T> pollingState; try { pollingState = new PollingState<>(response, this.getLongRunningOperationRetryTimeout(), resourceType); } catch (IOException e) { callback.failure(e); return null; } // Task runner will take it from here PostDeletePollingTask<T> task = new PostDeletePollingTask<>(pollingState, callback); executor.schedule(task, pollingState.getDelayInMilliseconds(), TimeUnit.MILLISECONDS); return task; }
From source file:com.microsoft.rest.ServiceResponseBuilder.java
License:Open Source License
/** * Builds the body object from the HTTP status code and returned response * body undeserialized and wrapped in {@link ResponseBody}. * * @param statusCode the HTTP status code * @param responseBody the response body * @return the response body, deserialized * @throws IOException thrown for any deserialization errors */// w w w .j a v a 2s .c o m protected Object buildBody(int statusCode, ResponseBody responseBody) throws IOException { if (responseBody == null) { return null; } Type type; if (responseTypes.containsKey(statusCode)) { type = responseTypes.get(statusCode); } else if (responseTypes.get(0) != Object.class) { type = responseTypes.get(0); } else { type = new TypeReference<T>() { }.getType(); } // Void response if (type == Void.class) { return null; } // Return raw response if InputStream is the target type else if (type == InputStream.class) { return responseBody.byteStream(); } // Deserialize else { String responseContent = responseBody.string(); if (responseContent.length() <= 0) { return null; } return mapperAdapter.deserialize(responseContent, type); } }
From source file:com.shekhargulati.reactivex.docker.client.DefaultRxDockerClient.java
License:Open Source License
@Override public Observable<DockerContainerResponse> createContainerObs(final DockerContainerRequest request, final Optional<String> name) { String content = request.toJson(); logger.info("Creating container for json request >>\n'{}'", content); final String uri = name.isPresent() ? CREATE_CONTAINER_ENDPOINT + "?name=" + name.get() : CREATE_CONTAINER_ENDPOINT; return httpClient.post(uri, content, (ResponseBody body) -> gson.fromJson(body.string(), DockerContainerResponse.class)); }
From source file:io.fabric8.kubernetes.client.dsl.base.OperationSupport.java
License:Apache License
public static Status createStatus(Response response) { int statusCode = response.code(); String statusMessage = ""; ResponseBody body = response != null ? response.body() : null; try {/*w ww .java 2 s . c om*/ if (response == null) { statusMessage = "No response"; } else if (body != null) { statusMessage = body.string(); } else if (response.message() != null) { statusMessage = response.message(); } return JSON_MAPPER.readValue(statusMessage, Status.class); } catch (JsonParseException e) { return createStatus(statusCode, statusMessage); } catch (IOException e) { return createStatus(statusCode, statusMessage); } }
From source file:io.github.tjg1.library.norilib.clients.Danbooru.java
@Override public SearchResult search(String tags, int pid) throws IOException { // Create HTTP request. final Request request = new Request.Builder().url(createSearchURL(tags, pid, DEFAULT_LIMIT)).build(); // Get HTTP response. final Response response = okHttpClient.newCall(request).execute(); final ResponseBody responseBody = response.body(); final String body = responseBody.string(); responseBody.close();// w ww.j a va 2 s .c om // Return parsed SearchResult. return parseXMLResponse(body, tags, pid); }
From source file:meteor.operations.Meteor.java
License:Apache License
/** * Returns a new instance for a client connecting to a server via DDP over websocket * <p>//from w w w. j av a 2 s . co m * The server URI should usually be in the form of `ws://example.meteor.com/websocket` * or `wss://example.meteor.com/websocket` * * @param persistence a `Context` reference (e.g. an `Activity` or `Service` instance) * @param serverUri the server URI to connect to * @param protocolVersion the desired DDP protocol version, default version if null given */ public Meteor(final Persistence persistence, final String serverUri, String protocolVersion) { if (protocolVersion == null) { protocolVersion = SUPPORTED_DDP_VERSIONS[0]; } else if (!isVersionSupported(protocolVersion)) { throw new RuntimeException("DDP protocol version not supported: " + protocolVersion); } if (persistence == null) { throw new RuntimeException("The Persistence reference may not be null"); } // save the context reference this.mPersistence = persistence; mWebSocketObserver = new WebSocketListener() { @Override public void onOpen(WebSocket webSocket, Response response) { mConnecting = false; mReconnectAttempts = 0; mConnection = webSocket; connect(mSessionID); } @Override public void onFailure(IOException e, Response response) { if (mCallback != null) { mCallback.onException(e); } } @Override public void onMessage(ResponseBody message) throws IOException { handleMessage(message.string()); } @Override public void onPong(Buffer payload) { } @Override public void onClose(int code, String reason) { if (code != CloseCode.NORMAL) { mConnecting = false; mConnection = null; mReconnectAttempts++; if (mReconnectAttempts <= RECONNECT_ATTEMPTS_MAX) { // try to re-connect automatically openConnection(false); } } else { mReconnectAttempts = 0; mListeners.clear(); mSessionID = null; mConnecting = false; } if (mCallback != null) { mCallback.onDisconnect(code, reason); } } }; // create a map that holds the pending Listener instances mListeners = new HashMap<String, Listener>(); // save the server URI mServerUri = serverUri; // try with the preferred DDP protocol version first mDdpVersion = protocolVersion; // count the number of failed attempts to re-connect mReconnectAttempts = 0; }
From source file:org.dkf.jed2k.util.http.OKHTTPClient.java
License:Open Source License
@Override public String get(String url, int timeout, String userAgent, String referrer, String cookie, Map<String, String> customHeaders) throws IOException { String result = null;//from w w w. j av a 2s.co m final OkHttpClient okHttpClient = newOkHttpClient(); final Request.Builder builder = prepareRequestBuilder(okHttpClient, url, timeout, userAgent, referrer, cookie); addCustomHeaders(customHeaders, builder); ResponseBody responseBody = null; try { responseBody = getSyncResponse(okHttpClient, builder).body(); result = responseBody.string(); } catch (IOException ioe) { //ioe.printStackTrace(); throw ioe; } catch (Throwable e) { LOG.error(e.getMessage(), e); } finally { if (responseBody != null) { closeQuietly(responseBody); } } return result; }
From source file:org.fs.ghanaian.core.CoreCallback.java
License:Apache License
/*** * * @param response//w w w.j ava 2 s . c o m * @throws IOException */ @Override public void onResponse(Response response) throws IOException { int httpCode = response.code(); if (httpCode == 200) { if (response != null) { ResponseBody body = response.body(); if (body != null) { String raw = body.string(); if (!StringUtility.isNullOrEmpty(raw)) { T object = parse(raw); result(httpCode, object); return; } } } } result(httpCode, null); }