/** Get events filtered by program orgUnit and between dates. */ public static List<Event> getEvents(String program, String orgUnit, Date minDate, Date maxDate) { try { Response response; String DHIS_URL = PreferencesState.getInstance().getDhisURL(); String startDate = EventExtended.format(minDate, EventExtended.AMERICAN_DATE_FORMAT); String endDate = EventExtended.format( new Date(maxDate.getTime() + (8 * 24 * 60 * 60 * 1000)), EventExtended.AMERICAN_DATE_FORMAT); String url = String.format(DHIS_URL + DHIS_CHECK_EVENT_API, program, orgUnit, startDate, endDate); Log.d(TAG, url); url = ServerAPIController.encodeBlanks(url); response = ServerAPIController.executeCall(null, url, "GET"); if (!response.isSuccessful()) { Log.e(TAG, "pushData (" + response.code() + "): " + response.body().string()); throw new IOException(response.message()); } JSONObject events = new JSONObject(response.body().string()); ObjectMapper mapper = new ObjectMapper(); JsonNode jsonNode = mapper.convertValue(mapper.readTree(events.toString()), JsonNode.class); return EventsWrapper.getEvents(jsonNode); } catch (Exception ex) { ex.printStackTrace(); return null; } }
@Override protected HttpResponse invoke(Request nativeRequest) throws IOException, InterruptedException { OkHttpClient requestScopedClient = globalClient.clone(); requestScopedClient.setProxy(proxyForURI.apply(nativeRequest.uri())); Response response = requestScopedClient.newCall(nativeRequest).execute(); HttpResponse.Builder<?> builder = HttpResponse.builder(); builder.statusCode(response.code()); builder.message(response.message()); Builder<String, String> headerBuilder = ImmutableMultimap.builder(); Headers responseHeaders = response.headers(); for (String header : responseHeaders.names()) { headerBuilder.putAll(header, responseHeaders.values(header)); } ImmutableMultimap<String, String> headers = headerBuilder.build(); if (response.code() == 204 && response.body() != null) { response.body().close(); } else { Payload payload = newInputStreamPayload(response.body().byteStream()); contentMetadataCodec.fromHeaders(payload.getContentMetadata(), headers); builder.payload(payload); } builder.headers(filterOutContentHeaders(headers)); return builder.build(); }
private String sendPop(Transaction tx) { RequestBody requestBody = RequestBody.create(MediaType.parse("application/bitcoin-pop"), tx.toBytes()); URL url; try { url = new URL(popRequest.getP()); if (!"http".equals(url.getProtocol()) && !"https".equals(url.getProtocol())) { return "Invalid Url, expected protocol http or https: " + popRequest.getP(); } } catch (MalformedURLException e) { return "Invalid Url: " + popRequest.getP(); } Request request = new Request.Builder().url(url).post(requestBody).build(); OkHttpClient httpClient = new OkHttpClient(); if (_mbwManager.getTorMode() == ServerEndpointType.Types.ONLY_TOR && _mbwManager.getTorManager() != null) { httpClient = _mbwManager.getTorManager().setupClient(httpClient); } try { Response response = httpClient.newCall(request).execute(); if (response.isSuccessful()) { return response.body().string(); } else { return "Error occurred: " + response.code(); } } catch (IOException e) { return "Cannot communicate with server: " + e.getMessage(); } }
@Override public Drawable getDrawable(final String source) { try { Drawable repositoryImage = requestRepositoryImage(source); if (repositoryImage != null) return repositoryImage; } catch (Exception e) { // Ignore and attempt request over regular HTTP request } try { String logMessage = "Loading image: " + source; Log.d(getClass().getSimpleName(), logMessage); Bugsnag.leaveBreadcrumb(logMessage); Request request = new Request.Builder().get().url(source).build(); com.squareup.okhttp.Response response = okHttpClient.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected response code: " + response.code()); Bitmap bitmap = BitmapFactory.decodeStream(response.body().byteStream()); if (bitmap == null) return loading.getDrawable(source); BitmapDrawable drawable = new BitmapDrawable(context.getResources(), bitmap); drawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight()); return drawable; } catch (IOException e) { Log.e(getClass().getSimpleName(), "Error loading image", e); Bugsnag.notify(e); return loading.getDrawable(source); } }
@Override public Response intercept(final Chain chain) throws IOException { long t1 = System.nanoTime(); final Request request = chain.request(); Log.v( NextClient.TAG, String.format( "[OkHttp Request] %s %s on %s%n", request.method(), request.url(), chain.connection())); if (mHeaders) { Log.v(NextClient.TAG, "[Request Headers] " + request.headers()); } final Response response = chain.proceed(request); long t2 = System.nanoTime(); Log.v( NextClient.TAG, String.format( "[OkHttp Response] %s %s (%s:%s) in %.1fms%n ", request.method(), request.url(), response.code(), response.message(), (t2 - t1) / 1e6d)); if (mHeaders) { Log.v(NextClient.TAG, "[Response Headers] " + response.headers()); } if (mBody) { Log.v(NextClient.TAG, "[OkHttp Response Body] " + responseToText(response)); } return response; }
private void logRequest(Request request, Response response, String body) throws IOException { if (Config.LOGS_ENABLED) { String requestString = request.method() + " " + request.urlString(); if (!request.method().toLowerCase().equals("get")) { Buffer buffer = new Buffer(); request.body().writeTo(buffer); requestString += " " + buffer.readUtf8(); } if (response.code() >= 400) { LogHelper.d(TAG, "request failed " + requestString); } else { LogHelper.d(TAG, "request success " + requestString); } LogHelper.i(TAG, "response = " + response.code() + " " + body); } }
/** * Execute HTTP call and deserialize the HTTP response body into the given return type. * * @param returnType The return type used to deserialize HTTP response body * @param <T> The return type corresponding to (same with) returnType * @param call Call * @return ApiResponse object containing response status, headers and data, which is a Java object * deserialized from response body and would be null when returnType is null. * @throws ApiException If fail to execute the call */ public <T> ApiResponse<T> execute(Call call, Type returnType) throws ApiException { try { Response response = call.execute(); T data = handleResponse(response, returnType); return new ApiResponse<T>(response.code(), response.headers().toMultimap(), data); } catch (IOException e) { throw new ApiException(e); } }
public Entry(Response response) { this.url = response.request().urlString(); this.varyHeaders = OkHeaders.varyHeaders(response); this.requestMethod = response.request().method(); this.requestBody = response.request().body(); this.protocol = response.protocol(); this.code = response.code(); this.message = response.message(); this.responseHeaders = response.headers(); this.handshake = response.handshake(); }
@Override public DeleteObjectResult parse(Response response) throws IOException { DeleteObjectResult result = new DeleteObjectResult(); try { result.setRequestId(response.header(OSSHeaders.OSS_HEADER_REQUEST_ID)); result.setStatusCode(response.code()); result.setResponseHeader(parseResponseHeader(response)); return result; } finally { safeCloseResponse(response); } }
private boolean IsNetBackend() { try { OkHttpClient httpclient = new OkHttpClient(); Request request = new Request.Builder() .url(getMobileServiceURL() + "api/runtimeinfo") .addHeader("ZUMO-API-VERSION", "2.0.0") .build(); Response response = httpclient.newCall(request).execute(); String runtimeType; if (response.code() == 200) { ByteArrayOutputStream out = new ByteArrayOutputStream(); String responseString = response.body().string(); JsonObject jsonResult = new JsonParser().parse(responseString).getAsJsonObject(); runtimeType = jsonResult.get("runtime").getAsJsonObject().get("type").getAsString(); out.close(); } else { response.body().close(); throw new IOException(String.valueOf(response.code())); } if (runtimeType.equals(".NET")) { return true; } return false; } catch (Exception ex) { return false; } }
@Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); Response response = chain.proceed(request); if (response.code() == HttpURLConnection.HTTP_UNAUTHORIZED || response.code() == HttpURLConnection.HTTP_FORBIDDEN) { String token = ApiClient.getAccessToken(); if (!TextUtils.isEmpty(token)) { LogUtil.v(TAG, "Token is no longer valid"); synchronized (sLock) { String currentToken = ApiClient.getAccessToken(); // Check if our current token has been updated, if it hasn't fetch a new one. if (!TextUtils.isEmpty(currentToken) && currentToken.equals(token)) { ApiClient.setAccessToken(refreshToken(OpengurApp.getInstance())); } } if (!TextUtils.isEmpty(ApiClient.getAccessToken())) { Request newRequest = request .newBuilder() .removeHeader(ApiClient.AUTHORIZATION_HEADER) .addHeader(ApiClient.AUTHORIZATION_HEADER, "Bearer " + ApiClient.getAccessToken()) .build(); return chain.proceed(newRequest); } } else { LogUtil.w(TAG, "Received unauthorized status from API but no access token present... wat?"); } } return response; }
@Override public AbortMultipartUploadResult parse(Response response) throws IOException { try { AbortMultipartUploadResult result = new AbortMultipartUploadResult(); result.setRequestId(response.header(OSSHeaders.OSS_HEADER_REQUEST_ID)); result.setStatusCode(response.code()); result.setResponseHeader(parseResponseHeader(response)); return result; } finally { safeCloseResponse(response); } }
@Override public GetBucketACLResult parse(Response response) throws IOException { try { GetBucketACLResult result = parseGetBucketACLResponse(response.body().byteStream()); result.setRequestId(response.header(OSSHeaders.OSS_HEADER_REQUEST_ID)); result.setStatusCode(response.code()); result.setResponseHeader(parseResponseHeader(response)); return result; } catch (Exception e) { throw new IOException(e.getMessage(), e); } finally { safeCloseResponse(response); } }
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { OkHttpClient client = okHttpClient.clone(); int timeoutMs = request.getTimeoutMs(); client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS); com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder(); okHttpRequestBuilder.url(request.getUrl()); Map<String, String> headers = request.getHeaders(); for (final String name : headers.keySet()) { okHttpRequestBuilder.addHeader(name, headers.get(name)); } for (final String name : additionalHeaders.keySet()) { okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name)); } setConnectionParametersForRequest(okHttpRequestBuilder, request); com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build(); Call okHttpCall = client.newCall(okHttpRequest); Response okHttpResponse = okHttpCall.execute(); StatusLine responseStatus = new BasicStatusLine( parseProtocol(okHttpResponse.protocol()), okHttpResponse.code(), okHttpResponse.message()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromOkHttpResponse(okHttpResponse)); Headers responseHeaders = okHttpResponse.headers(); for (int i = 0, len = responseHeaders.size(); i < len; i++) { final String name = responseHeaders.name(i), value = responseHeaders.value(i); if (name != null) { response.addHeader(new BasicHeader(name, value)); } } return response; }
@Override public GetObjectResult parse(Response response) throws IOException { GetObjectResult result = new GetObjectResult(); result.setRequestId(response.header(OSSHeaders.OSS_HEADER_REQUEST_ID)); result.setStatusCode(response.code()); result.setResponseHeader(parseResponseHeader(response)); result.setMetadata(parseObjectMetadata(result.getResponseHeader())); result.setContentLength(response.body().contentLength()); result.setObjectContent(response.body().byteStream()); // keep body stream open for reading content return result; }
/** * Handle the given response, return the deserialized object when the response is successful. * * @param <T> Type * @param response Response * @param returnType Return type * @throws ApiException If the response has a unsuccessful status code or fail to deserialize the * response body * @return Type */ public <T> T handleResponse(Response response, Type returnType) throws ApiException { if (response.isSuccessful()) { if (returnType == null || response.code() == 204) { // returning null if the returnType is not defined, // or the status code is 204 (No Content) return null; } else { return deserialize(response, returnType); } } else { String respBody = null; if (response.body() != null) { try { respBody = response.body().string(); } catch (IOException e) { throw new ApiException( response.message(), e, response.code(), response.headers().toMultimap()); } } throw new ApiException( response.message(), response.code(), response.headers().toMultimap(), respBody); } }
@Override public CopyObjectResult parse(Response response) throws IOException { try { CopyObjectResult result = parseCopyObjectResponseXML(response.body().byteStream()); result.setRequestId(response.header(OSSHeaders.OSS_HEADER_REQUEST_ID)); result.setStatusCode(response.code()); result.setResponseHeader(parseResponseHeader(response)); return result; } catch (Exception e) { e.printStackTrace(); throw new IOException(e.getMessage(), e); } finally { safeCloseResponse(response); } }
@Override public InitiateMultipartUploadResult parse(Response response) throws IOException { try { InitiateMultipartUploadResult result = parseInitMultipartResponseXML(response.body().byteStream()); result.setRequestId(response.header(OSSHeaders.OSS_HEADER_REQUEST_ID)); result.setStatusCode(response.code()); result.setResponseHeader(parseResponseHeader(response)); return result; } catch (Exception e) { throw new IOException(e.getMessage(), e); } }
@Override public UploadPartResult parse(Response response) throws IOException { try { UploadPartResult result = new UploadPartResult(); result.setRequestId(response.header(OSSHeaders.OSS_HEADER_REQUEST_ID)); result.setStatusCode(response.code()); result.setResponseHeader(parseResponseHeader(response)); result.setETag(trimQuotes(response.header(OSSHeaders.ETAG))); return result; } finally { safeCloseResponse(response); } }
@Override public void onResponse(final Response response) throws IOException { try { final int statusCode = response.code(); final String responseString = response.body().string(); T t = parse(responseString); sendOnSuccessMessage(statusCode, t); } catch (final IOException e) { sendOnErrorMessage(response.request(), e); e.printStackTrace(); } catch (final JsonParseException e) { sendOnErrorMessage(response.request(), new JsonParseException("parse failure")); e.printStackTrace(); } }
/** * Deserialize response body to Java object, according to the return type and the Content-Type * response header. * * @param <T> Type * @param response HTTP response * @param returnType The type of the Java object * @return The deserialized Java object * @throws ApiException If fail to deserialize response body, i.e. cannot read response body or * the Content-Type of the response is not supported. */ @SuppressWarnings("unchecked") public <T> T deserialize(Response response, Type returnType) throws ApiException { if (response == null || returnType == null) { return null; } if ("byte[]".equals(returnType.toString())) { // Handle binary response (byte array). try { return (T) response.body().bytes(); } catch (IOException e) { throw new ApiException(e); } } else if (returnType.equals(File.class)) { // Handle file downloading. return (T) downloadFileFromResponse(response); } String respBody; try { if (response.body() != null) respBody = response.body().string(); else respBody = null; } catch (IOException e) { throw new ApiException(e); } if (respBody == null || "".equals(respBody)) { return null; } String contentType = response.headers().get("Content-Type"); if (contentType == null) { // ensuring a default content type contentType = "application/json"; } if (isJsonMime(contentType)) { return json.deserialize(respBody, returnType); } else if (returnType.equals(String.class)) { // Expecting string, return the raw response body. return (T) respBody; } else { throw new ApiException( "Content type \"" + contentType + "\" is not supported for type: " + returnType, response.code(), response.headers().toMultimap(), respBody); } }
public static boolean hasBody(Response response) { if (!response.request().method().equals("HEAD")) { int j = response.code(); if ((j < 100 || j >= 200) && j != 204 && j != 304) { return true; } if (OkHeaders.contentLength(response) != -1L || "chunked".equalsIgnoreCase(response.header("Transfer-Encoding"))) { return true; } } return false; }
@Override protected Void doInBackground(OnResponseListener... params) { OnResponseListener l = params[0]; OkHttpClient httpClient = new OkHttpClient(); Request request = new Request.Builder().url(QUESTIONS_ENDPOINT).build(); try { Response response = httpClient.newCall(request).execute(); l.onResponse(new ServerResponse(response.code(), response.body().string())); } catch (IOException e) { l.onResponse(new ServerResponse(404, "[]")); } return null; }
private InputStream getInputStream(String urlStr) throws IOException { Request request = WallabagConnection.getRequest(WallabagConnection.getHttpURL(urlStr)); Response response = WallabagConnection.getClient().newCall(request).execute(); if (response.isSuccessful()) { return response.body().byteStream(); } else { // TODO: fix throw new RuntimeException( String.format( App.getInstance().getString(R.string.unsuccessfulRequest_errorMessage), response.code(), response.message())); } }
/** * Checks if the response status code is the expected and throws the appropriate * KubernetesClientException if not. * * @param request The {#link Request} object. * @param response The {@link Response} object. * @param expectedStatusCode The expected status code. * @throws KubernetesClientException When the response code is not the expected. */ protected void assertResponseCode(Request request, Response response, int expectedStatusCode) { int statusCode = response.code(); String customMessage = config.getErrorMessages().get(statusCode); if (statusCode == expectedStatusCode) { return; } else if (customMessage != null) { throw requestFailure(request, createStatus(statusCode, customMessage)); } else { try { Status status = JSON_MAPPER.readValue(response.body().byteStream(), Status.class); throw requestFailure(request, status); } catch (IOException e) { throw requestFailure(request, createStatus(statusCode, "")); } } }
public static @NonNull SmashNetworkData perform(SmashRequest<?> request) throws SmashError { SmashNetworkData data = new SmashNetworkData(); try { Request.Builder okBuilder = new Request.Builder().url(request.getUrl()); okBuilder.removeHeader("User-Agent").addHeader("User-Agent", Smash.getUserAgent()); BufferedSource body = getBody(request); switch (request.getMethod()) { case GET: okBuilder = okBuilder.get(); break; case POST: okBuilder = okBuilder.post(convertBody(request, body)); break; case PUT: okBuilder = okBuilder.put(convertBody(request, body)); break; case DELETE: okBuilder = okBuilder.delete(convertBody(request, body)); break; case HEAD: okBuilder = okBuilder.head(); break; case PATCH: okBuilder = okBuilder.patch(convertBody(request, body)); break; } Request okRequest = okBuilder.build(); Response okResponse = sHttpClient.newCall(okRequest).execute(); if (body != null) { body.close(); } data.code = okResponse.code(); data.headers = okResponse.headers(); data.source = okResponse.body().source(); data.length = okResponse.body().contentLength(); } catch (IOException ioe) { throw new SmashError(ioe); } return data; }
protected String get(String url) throws IOException, ApiException, JSONException { String responseString = ""; OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(url).build(); Response response = client.newCall(request).execute(); responseString = response.body().string(); if (!response.isSuccessful()) { handleError(response.code(), request.uri() + "", responseString); } return responseString; }
@Override public PutObjectResult parse(Response response) throws IOException { try { PutObjectResult result = new PutObjectResult(); result.setRequestId(response.header(OSSHeaders.OSS_HEADER_REQUEST_ID)); result.setStatusCode(response.code()); result.setResponseHeader(parseResponseHeader(response)); result.setETag(trimQuotes(response.header(OSSHeaders.ETAG))); if (response.body().contentLength() > 0) { result.setServerCallbackReturnBody(response.body().string()); } return result; } finally { safeCloseResponse(response); } }
public static ServiceException parseResponseErrorXML(Response response, boolean isHeadRequest) throws IOException { int statusCode = response.code(); String requestId = response.header(OSSHeaders.OSS_HEADER_REQUEST_ID); String code = null; String message = null; String hostId = null; String errorMessage = null; if (!isHeadRequest) { try { errorMessage = response.body().string(); DocumentBuilder builder = domFactory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(errorMessage)); Document dom = builder.parse(is); Element element = dom.getDocumentElement(); NodeList list = element.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node item = list.item(i); String name = item.getNodeName(); if (name == null) continue; if (name.equals("Code")) { code = checkChildNotNullAndGetValue(item); } if (name.equals("Message")) { message = checkChildNotNullAndGetValue(item); } if (name.equals("RequestId")) { requestId = checkChildNotNullAndGetValue(item); } if (name.equals("HostId")) { hostId = checkChildNotNullAndGetValue(item); } } } catch (SAXException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } } return new ServiceException(statusCode, message, code, requestId, hostId, errorMessage); }
private <T> Observable<T> makeRequest(final Request.Builder builder, final Type type) { return Observable.create( (final Subscriber<? super T> subscriber) -> { ApiUtils.executeWithRuntimeException( () -> { Request request = builder.build(); Response response = getHttpClient().newCall(request).execute(); String body = response.body().string(); logRequest(request, response, body); if (response.code() >= 400) { throw new RuntimeException("failed"); } T result = gson.fromJson(body, type); subscriber.onNext(result); subscriber.onCompleted(); }); }); }