List of usage examples for com.squareup.okhttp Response body
ResponseBody body
To view the source code for com.squareup.okhttp Response body.
Click Source Link
From source file:com.anony.okhttp.sample.PostStreaming.java
License:Apache License
public void run() throws Exception { RequestBody requestBody = new RequestBody() { @Override//w w w . j av a 2 s. c om public MediaType contentType() { return MEDIA_TYPE_MARKDOWN; } @Override public void writeTo(BufferedSink sink) throws IOException { sink.writeUtf8("Numbers\n"); sink.writeUtf8("-------\n"); for (int i = 2; i <= 997; i++) { sink.writeUtf8(String.format(" * %s = %s\n", i, factor(i))); } } private String factor(int n) { for (int i = 2; i < n; i++) { int x = n / i; if (x * i == n) return factor(x) + " " + i; } return Integer.toString(n); } }; Request request = new Request.Builder().url("https://api.github.com/markdown/raw").post(requestBody) .build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println(response.body().string()); }
From source file:com.anony.okhttp.sample.PostString.java
License:Apache License
public void run() throws Exception { String postBody = "" + "Releases\n" + "--------\n" + "\n" + " * _1.0_ May 6, 2013\n" + " * _1.1_ June 15, 2013\n" + " * _1.2_ August 11, 2013\n"; Request request = new Request.Builder().url("https://api.github.com/markdown/raw") .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody)).build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println(response.body().string()); }
From source file:com.anony.okhttp.sample.Progress.java
License:Apache License
public void run() throws Exception { Request request = new Request.Builder().url("https://publicobject.com/helloworld.txt").build(); final ProgressListener progressListener = new ProgressListener() { @Override//from ww w.j a va 2s . co m public void update(long bytesRead, long contentLength, boolean done) { System.out.println(bytesRead); System.out.println(contentLength); System.out.println(done); System.out.format("%d%% done\n", (100 * bytesRead) / contentLength); } }; client.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(); } }); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println(response.body().string()); }
From source file:com.anony.okhttp.sample.RequestBodyCompression.java
License:Apache License
public void run() throws Exception { Map<String, String> requestBody = new LinkedHashMap<>(); requestBody.put("longUrl", "https://publicobject.com/2014/12/04/html-formatting-javadocs/"); RequestBody jsonRequestBody = RequestBody.create(MEDIA_TYPE_JSON, new Gson().toJson(requestBody)); Request request = new Request.Builder() .url("https://www.googleapis.com/urlshortener/v1/url?key=" + GOOGLE_API_KEY).post(jsonRequestBody) .build();//from ww w . ja v a 2s .co m Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println(response.body().string()); }
From source file:com.anony.okhttp.sample.RewriteResponseCacheControl.java
License:Apache License
public void run() throws Exception { for (int i = 0; i < 5; i++) { System.out.println(" Request: " + i); Request request = new Request.Builder().url("https://api.github.com/search/repositories?q=http") .build();// www . jav a2s . c o m if (i == 2) { // Force this request's response to be written to the cache. This way, subsequent responses // can be read from the cache. System.out.println("Force cache: true"); client.networkInterceptors().add(REWRITE_CACHE_CONTROL_INTERCEPTOR); } else { System.out.println("Force cache: false"); client.networkInterceptors().clear(); } Response response = client.newCall(request).execute(); response.body().close(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println(" Network: " + (response.networkResponse() != null)); System.out.println(); } }
From source file:com.apothesource.pillfill.network.PFNetworkManager.java
License:Open Source License
public static String doPinnedGetForUrl(String url) throws IOException { OkHttpClient client = getPinnedPFHttpClient(); Request.Builder requestBuilder = new Request.Builder().url(url); Response response = client.newCall(requestBuilder.build()).execute(); return response.body().string(); }
From source file:com.apothesource.pillfill.network.PFNetworkManager.java
License:Open Source License
public static String doPinnedGetForUrl(String url, String authToken) throws IOException { OkHttpClient client = getPinnedPFHttpClient(); Request.Builder requestBuilder = new Request.Builder().url(url); if (authToken != null) requestBuilder = requestBuilder.addHeader("Bearer", authToken); Response response = client.newCall(requestBuilder.build()).execute(); return response.body().string(); }
From source file:com.apothesource.pillfill.service.drug.impl.DefaultDrugAlertServiceImpl.java
License:Open Source License
@Override public Observable<DrugAlertType> checkForRxNormInteractions(Collection<PrescriptionType> rxList) { HashSet<String> cuiSet = new HashSet<>(); Observable<String> rxNormIdList = Observable.from(rxList).filter(rx -> rx.getRxNormId() != null) .map(PrescriptionType::getRxNormId); cuiSet.addAll(rxNormIdList.toList().toBlocking().first()); return subscribeIoObserveImmediate(Observable.create(subscriber -> { if (cuiSet.size() < 2) { log.fine("Not processing drug interaction set size of " + cuiSet.size()); subscriber.onCompleted();//from w w w .j ava 2s . c o m } else { // Check to see if this set has been queried before ArrayList<String> cuiList = new ArrayList<>(cuiSet); Collections.sort(cuiList); String param = Joiner.on("+").join(cuiList); final String url = String.format(PFServiceEndpoints.EXT_RXNORM_INTERACTIONS_URL, param); Optional<String> cachedResult = cache.getCachedData(url); if (cachedResult.isPresent()) { log.fine("Returning cached result for URL query: " + url); List<DrugAlertType> alertList = deserializeDrugAlerts(rxList, cachedResult.get()); Observable.from(alertList).forEach(subscriber::onNext); subscriber.onCompleted(); } else { log.fine("Requesting Interaction URL: " + url); Request.Builder rxNormInteractionCheckRequest = new Request.Builder(); Request req = rxNormInteractionCheckRequest.url(url).build(); try { Response responseObject = externalHttpClient.newCall(req).execute(); String responseMsg = responseObject.body().string(); cache.setCachedData(url, responseMsg); List<DrugAlertType> drugAlerts = deserializeDrugAlerts(rxList, responseMsg); Observable.from(drugAlerts).forEach(subscriber::onNext); subscriber.onCompleted(); } catch (IOException e) { log.log(Level.WARNING, "Error processing drug interaction response.", e); subscriber.onError(new RuntimeException(e)); } } } })); }
From source file:com.apothesource.pillfill.service.prescription.impl.DefaultPrescriptionServiceImpl.java
License:Open Source License
@Override public Observable<PrescriptionType> getPrescriptions(List<String> rxIds) { return subscribeIoObserveImmediate(subscriber -> { if (rxIds == null || rxIds.isEmpty()) { log.warning("Cannot load prescriptions- empty id list"); subscriber.onCompleted();/*w w w. j a v a 2s. c o m*/ } else { int idx = 0; while (idx < rxIds.size()) { int batchSize = (rxIds.size() - idx > 100) ? 100 : rxIds.size() - idx; List<String> reqList = rxIds.subList(idx, idx + batchSize); final String url = String.format(PFServiceEndpoints.PRESCRIPTIONS_URL, Joiner.on("%2C").skipNulls().join(reqList)); log.info(String.format("Requesting url: %s", url)); try { OkHttpClient connection = PFNetworkManager.getPinnedPFHttpClient(); Request request = new Request.Builder().url(url).addHeader("Cache-Control", "no-cache") .build(); Response response = connection.newCall(request).execute(); if (response.code() != 200) { subscriber.onError(new RuntimeException( String.format("Invalid response code: %d", response.code()))); return; } else { Type type = new TypeToken<ArrayList<PrescriptionType>>() { }.getType(); ArrayList<PrescriptionType> retList = gson.fromJson(response.body().string(), type); Observable.from(retList).forEach(subscriber::onNext); } } catch (Exception e) { subscriber.onError(e); return; } idx += batchSize; } subscriber.onCompleted(); } }); }
From source file:com.apothesource.pillfill.service.prescription.impl.DefaultPrescriptionServiceImpl.java
License:Open Source License
@Override public Observable<AccountAggregationTaskResponse> requestPrescriptionExtraction( AccountAggregationTaskRequest request) { return subscribeIoObserveImmediate(subscriber -> { String responseStr = null; try {/* w w w . jav a 2s. c o m*/ OkHttpClient client = PFNetworkManager.getPinnedPFHttpClient(); Request req = new Request.Builder() .post(RequestBody.create(MediaType.parse(HTTP_CONTENT_TYPE_JSON), gson.toJson(request))) .url(PFServiceEndpoints.RX_REQUEST_EXTRACT_URL).build(); Response res = client.newCall(req).execute(); responseStr = res.body().string(); AccountAggregationTaskResponse response = gson.fromJson(responseStr, AccountAggregationTaskResponse.class); subscriber.onNext(response); subscriber.onCompleted(); } catch (IOException e) { log.log(Level.SEVERE, "Communication error during extraction request."); subscriber.onError(e); } catch (JsonSyntaxException e) { log.severe(String.format("Error parsing response: %s", responseStr)); subscriber.onError(e); } }); }