@Test public void shouldSendGetRequest() throws ExecutionException, InterruptedException { final Request request = new com.squareup.okhttp.Request.Builder() .url(URI) .method("GET", null) .build(); when(okHttpClient.newCall(argThat(new RequestMatcher(request)))).thenReturn(call); doAnswer(invocation -> { final Callback callback = invocation.getArgument(0); callback.onResponse(new Response.Builder() .request(request) .protocol(Protocol.HTTP_1_1) .code(Status.OK.code()) .message("OK") .body(ResponseBody.create(CONTENT_TYPE, "{}")) .header("foo", "bar") .build()); return Void.TYPE; }).when(call).enqueue(isA(Callback.class)); final com.spotify.apollo.Response<ByteString> response = client.send(com.spotify.apollo.Request.forUri(URI, "GET")).toCompletableFuture().get(); verify(okHttpClient, never()).setReadTimeout(anyLong(), any()); assertEquals(Optional.of(ByteString.of("{}".getBytes())), response.payload()); assertEquals(Optional.of("bar"), response.header("foo")); }
@PostConstruct public void init() throws IOException { Map<String, String> headers = new HashMap<>(); String[] localVarAuthNames = new String[] { "BearerToken" }; List<Pair> queryParams = new ArrayList<>(); kc.updateParamsForAuth(localVarAuthNames, queryParams, headers); Request.Builder builder = new Request.Builder().url(kc.getBasePath() + "/version"); for (Map.Entry<String, String> header : headers.entrySet()) builder.addHeader(header.getKey(), header.getValue()); Call call = kc.getHttpClient().newCall(builder.get().build()); ResponseBody res = call.execute().body(); Map version = om.readValue(res.byteStream(), Map.class); String status = (String)version.get("status"); if ("Failure".equals(status)) throw new RuntimeException("/version returned " + status); major = Integer.parseInt((String) version.get("major")); minor = Integer.parseInt((String) version.get("minor")); }
@Override public Converter<ResponseBody, ?> fromResponseBody(Type type, Annotation[] annotations) { //noinspection EqualsBetweenInconvertibleTypes if (Document.class.equals(type)) { return new Converter<ResponseBody, Object>() { @Override public Object convert(ResponseBody responseBody) throws IOException { Document doc = Jsoup.parse(responseBody.string()); responseBody.close(); return doc; } }; } return null; }
private void loadAndParseConfig() { Call<Config> call = ApiClient.getInstance().getApiService().getConfig(); call.enqueue(new Callback<Config>() { @Override public void onResponse(Response<Config> response, Retrofit retrofit) { if (response.isSuccess()) { Log.d("config received"); config = response.body(); getTaxonomyData(); } else { int statusCode = response.code(); Log.d("Config data not received. Error code : " + statusCode); ResponseBody errorBody = response.errorBody(); handleError(); } } @Override public void onFailure(Throwable t) { Log.d("config data request failed"); handleError(); } }); }
public MPost sendPost(MPost toSend) throws IOException { String url = host + "api/v3/teams/" + toSend.getTeamId() + "/channels/" + toSend.getChannelId() + "/posts/create"; String dataToSend = gson.toJson(toSend); Request r = auth(new Request.Builder()).url(url) .post(RequestBody.create(MediaType.parse("application/json"), dataToSend)).build(); Response response = client.newCall(r).execute(); try (ResponseBody body = response.body()) { if (response.isSuccessful()) { MPost msg = gson.fromJson(body.string(), MPost.class); msg.setTeamId(toSend.getTeamId()); return msg; } } return null; }
private ResponseBody fetchFromNetwork(Uri url, int staleness) { Request.Builder builder = new Request.Builder(); builder.url(url.toString()); if (staleness > 0) { builder.cacheControl(allowStaleCache(staleness)); } Request request = builder.build(); client.setConnectTimeout(10, TimeUnit.SECONDS); client.setReadTimeout(60, TimeUnit.SECONDS); Log.d(TAG, "Requesting URL:" + request.urlString()); try { Response response = client.newCall(request).execute(); if (response.cacheResponse() != null) { Log.d(TAG, "Cached response [" + response.code() + "]:" + request.urlString()); } else { Log.d(TAG, "Network response [" + response.code() + "]:" + request.urlString()); } if (response.isSuccessful()) { return response.body(); } } catch (IOException e) { e.printStackTrace(); } return null; }
@Override public void onResponse(Response response) throws IOException { if (!response.isSuccessful()) { postOnFailure(parseUnsuccessfulResponse(response)); return; } ResponseBody body = response.body(); try { Reader charStream = body.charStream(); T payload = getAdapter().fromJson(charStream); postOnSuccess(payload); } catch (IOException e) { final Auth0Exception auth0Exception = new Auth0Exception("Failed to parse response to request to " + url, e); postOnFailure(getErrorBuilder().from("Failed to parse a successful response", auth0Exception)); } finally { closeStream(body); } }
@Override protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException { Request request = new Request.Builder().url(imageUri).build(); ResponseBody responseBody = client.newCall(request).execute().body(); InputStream inputStream = responseBody.byteStream(); int contentLength = (int) responseBody.contentLength(); return new ContentLengthInputStream(inputStream, contentLength); }
private static HttpEntity entityFromOkHttpResponse(Response r) throws IOException { BasicHttpEntity entity = new BasicHttpEntity(); ResponseBody body = r.body(); entity.setContent(body.byteStream()); entity.setContentLength(body.contentLength()); entity.setContentEncoding(r.header("Content-Encoding")); if (body.contentType() != null) { entity.setContentType(body.contentType().type()); } return entity; }
@Test public void shouldSendPostRequest() throws ExecutionException, InterruptedException { final Request request = new com.squareup.okhttp.Request.Builder() .url(URI) .method("POST", RequestBody.create(CONTENT_TYPE, "{}")) .build(); when(okHttpClient.newCall(argThat(new RequestMatcher(request)))).thenReturn(call); doAnswer(invocation -> { final Callback callback = invocation.getArgument(0); callback.onResponse(new Response.Builder() .request(request) .protocol(Protocol.HTTP_1_1) .code(Status.OK.code()) .message("OK") .body(ResponseBody.create(CONTENT_TYPE, "{}")) .header("foo", "bar") .build()); return Void.TYPE; }).when(call).enqueue(isA(Callback.class)); final com.spotify.apollo.Response<ByteString> response = client.send(com.spotify.apollo.Request .forUri(URI, "POST") .withPayload(ByteString.of("{}".getBytes()))) .toCompletableFuture().get(); verify(okHttpClient, never()).setReadTimeout(anyLong(), any()); assertEquals(Optional.of(ByteString.of("{}".getBytes())), response.payload()); assertEquals(Optional.of("bar"), response.header("foo")); }
/** * * @param body * @return */ private String unzip(ResponseBody body) { try { GzipSource responseBody = new GzipSource(body.source()); return Okio.buffer(responseBody).readUtf8(); } catch (IOException e) { return null; } }
/** * * @param params * @return */ @Override protected String doInBackground(Void... params) { OkHttpClient client = new OkHttpClient(); HttpUrl httpUrl = HttpUrl.parse(TwitterSearchURL); httpUrl = httpUrl.newBuilder() .addQueryParameter("q", _searchTerm) .addQueryParameter("lang", "en") .addQueryParameter("result_type", "recent") .build(); Request request = new Request.Builder() .url(httpUrl) .addHeader("Authorization", "Bearer " + _bearerToken) .addHeader("Accept-Encoding", "gzip") .build(); String content = null; try { Response response = client.newCall(request).execute(); ResponseBody body = response.body(); if (isZipped(response)) { content = unzip(body); } else { content = body.string(); } body.close(); } catch (IOException e) { e.printStackTrace(); } return content; }
/** * * @param params * @return */ @Override protected String doInBackground(Void... params) { OkHttpClient client = new OkHttpClient(); HttpUrl httpUrl = HttpUrl.parse(COIN_DESK_API_URL); //System.out.println("Requesting : " + httpUrl.toString()); FormEncodingBuilder formBody = new FormEncodingBuilder(); formBody.add("lastHours", "24"); formBody.add("maxRespArrSize", "24"); Request request = new Request.Builder() .url(httpUrl) .post(formBody.build()) .build(); String content = null; try { Response response = client.newCall(request).execute(); ResponseBody body = response.body(); if (isZipped(response)) { content = unzip(body); } else { content = body.string(); } body.close(); } catch (IOException e) { e.printStackTrace(); } return content; }
@Override public void onMessage(ResponseBody body) throws IOException { if (body.contentType() == TEXT) { listener.textMessage(body.charStream()); } else if (body.contentType() == BINARY) { listener.bytesMessage(body.byteStream()); } body.close(); }
@Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); Response response = null; try { Log.i(TAG, "request is: \n" + request.toString()); Log.i(TAG, "request headers are: \n" + request.headers().toString()); Buffer buffer = new Buffer(); if (request.body() != null) { request.body().writeTo(buffer); } String bodyStr = buffer.readUtf8(); Log.i(TAG, "REQUEST body is: \n" + bodyStr); response = chain.proceed(request); String responseBodyString = ""; MediaType type = null; if (response.body() != null) { type = response.body().contentType(); responseBodyString = response.body().string(); } response = response.newBuilder().body(ResponseBody.create(type, responseBodyString.getBytes())).build(); Log.i(TAG, "RESPONSE body is \n" + responseBodyString); return response; } catch (Exception e) { Log.e(TAG, "RequestInterceptor: intercept", e); } return response; }
private void readWithProgress( ExecutorToken executorToken, int requestId, ResponseBody responseBody) throws IOException { Reader reader = responseBody.charStream(); try { StringBuilder sb = new StringBuilder(getBufferSize(responseBody)); char[] buffer = new char[MIN_BUFFER_SIZE]; int read; long last = System.nanoTime(); while ((read = reader.read(buffer)) != -1) { sb.append(buffer, 0, read); long now = System.nanoTime(); if (shouldDispatch(now, last)) { onDataReceived(executorToken, requestId, sb.toString()); sb.setLength(0); last = now; } } if (sb.length() > 0) { onDataReceived(executorToken, requestId, sb.toString()); } } finally { reader.close(); } }
private static int getBufferSize(ResponseBody responseBody) throws IOException { long length = responseBody.contentLength(); if (length == -1) { return MIN_BUFFER_SIZE; } else { return (int) min(length, MAX_BUFFER_SIZE); } }
/** * Parse the error body by provide server format. */ public <T> T getErrorBodyAs(Class<T> type) throws IOException { if (response == null || response.errorBody() == null) { return null; } Converter<ResponseBody, T> converter = retrofit.responseConverter(type, new Annotation[0]); return converter.convert(response.errorBody()); }
@Override public T convert(ResponseBody value) throws IOException { BufferedSource bufferedSource = Okio.buffer(value.source()); String tempStr = bufferedSource.readUtf8(); bufferedSource.close(); return JSON.parseObject(tempStr, mType); }
@Override public T convert(ResponseBody value) throws IOException { InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; final StringBuilder stringBuilder = new StringBuilder(); try { inputStreamReader = (InputStreamReader) value.charStream(); bufferedReader = new BufferedReader(inputStreamReader); String content = null; while ((content = bufferedReader.readLine()) != null) { stringBuilder.append(content); } } finally { if (bufferedReader != null) { bufferedReader.close(); } if (inputStreamReader != null) { inputStreamReader.close(); } } final String json = stringBuilder.toString(); try { return gson.fromJson(json.replace("HeWeather data service 3.0", "decor"), type); }catch (Exception e) { return null; } }
private boolean downloadFile(@NonNull String url, @NonNull File targetFile) { LOGD(TAG, "Downloading \"" + url + "\" into \"" + targetFile + "\"..."); Request request = new Request.Builder().url(url).tag(OKHTTP_TAG).build(); Response response; try { response = mOkHttpClient.newCall(request).execute(); if (!response.isSuccessful()) { return false; } final ResponseBody body = response.body(); final InputStream inputStream = body.byteStream(); final OutputStream outputStream = new FileOutputStream(targetFile); byte[] buffer = new byte[BUFFER_SIZE]; int len; while ((len = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); mDownloaded += len; publishProgress((int) (mDownloaded * 100 / mSelectedMap.getMapSize())); } inputStream.close(); outputStream.close(); } catch (IOException e) { LOGE(TAG, "Cannot download map.", e); return false; } LOGD(TAG, "Downloaded."); return true; }
private void readWithProgress( ExecutorToken executorToken, int requestId, ResponseBody responseBody) throws IOException { Reader reader = responseBody.charStream(); try { char[] buffer = new char[MAX_CHUNK_SIZE_BETWEEN_FLUSHES]; int read; while ((read = reader.read(buffer)) != -1) { onDataReceived(executorToken, requestId, new String(buffer, 0, read)); } } finally { reader.close(); } }
private void getTaxonomies() { if (SharedPreferencesHelper.getCache()!=null && !SharedPreferencesHelper.getCache().getCachedTaxonomies().isEmpty()) { setup(SharedPreferencesHelper.getCache().getCachedTaxonomies()); } else { pagesContainer.setVisibility(View.GONE); progressBar.setVisibility(View.VISIBLE); Call<TaxonomiesResponse> call = ApiClient.getInstance().getApiService().getAllTaxonomies(); call.enqueue(new Callback<TaxonomiesResponse>() { @Override public void onResponse(Response<TaxonomiesResponse> response, Retrofit retrofit) { Log.d("Taxonomies data request succeeded"); if (response.isSuccess()) { Log.d("Taxonomies received"); TaxonomiesResponse taxonomiesResponse = response.body(); ArrayList<Taxonomy> taxonomies = new ArrayList<Taxonomy>(); taxonomies.addAll(taxonomiesResponse.getTaxonomies()); Cache cache = Cache.get(); cache.getCachedTaxonomies().clear(); cache.getCachedTaxonomies().addAll(taxonomies); SharedPreferencesHelper.saveCache(cache); pagesContainer.setVisibility(View.GONE); progressBar.setVisibility(View.VISIBLE); setup(taxonomies); } else { int statusCode = response.code(); Log.d("Taxonomies not received. Error code : " + statusCode); ResponseBody errorBody = response.errorBody(); Log.d("Tax Error : " + errorBody.toString()); } } @Override public void onFailure(Throwable t) { Log.d("Taxonomies data request failed"); } }); } }
private void doLegacyRESTUploadTo(NightscoutService nightscoutService, List<BgReading> glucoseDataSets) throws Exception { for (BgReading record : glucoseDataSets) { Response<ResponseBody> r = nightscoutService.upload(populateLegacyAPIEntry(record)).execute(); if (!r.isSuccess()) throw new UploaderException(r.message(), r.code()); } try { postDeviceStatus(nightscoutService, null); } catch (Exception e) { Log.e(TAG, "Ignoring legacy devicestatus post exception: " + e); } }
public void upload(ShareUploadPayload bg) { shareRest.uploadBGRecords(bg, new Callback<ResponseBody>() { @Override public void onResponse(Response<ResponseBody> response, Retrofit retrofit) { // This should probably be pulled up into BgSendQueue or NightscoutUploader // where errors can be handled properly. } @Override public void onFailure(Throwable t) { // TODO add error handling in a refactoring pass } }); }
public void uploadBGRecords(final ShareUploadPayload bg, Callback<ResponseBody> callback) { dexcomShareApi.uploadBGRecords(getSessionId(), bg).enqueue(new AuthenticatingCallback<ResponseBody>(callback) { @Override public void onRetry() { dexcomShareApi.uploadBGRecords(getSessionId(), bg).enqueue(this); } }); }
public void deleteContact(final String contactId, Callback<ResponseBody> deleteFollowerListener) { dexcomShareApi.deleteContact(getSessionId(), contactId).enqueue(new AuthenticatingCallback<ResponseBody>(deleteFollowerListener) { @Override public void onRetry() { dexcomShareApi.deleteContact(getSessionId(), contactId).enqueue(this); } }); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); streetViewContainer = (ImageView) findViewById(R.id.streetImageContainer); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { StreetView streetView = new StreetView.Builder("ApiKey") .pitch("-0.76") .heading("80.0") .size("600x450") .fov("90") .build(); streetView.getStreetView(41.0421119, 29.0379787, new CallBack() { @Override public void onResponse(Response<ResponseBody> response, Retrofit retrofit, Bitmap bitmapStreetView) { streetViewContainer.setImageBitmap(bitmapStreetView); } @Override public void onFailure(Throwable t) { t.printStackTrace(); } }); } }); }
@Override public View getView(final int position, final View convertView, ViewGroup parent) { View view = convertView; if (view == null) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(R.layout.item_follower, null); } TextView followerName = (TextView) view.findViewById(R.id.follwerName); Button deleteButton = (Button) view.findViewById(R.id.deleteFollower); final ExistingFollower follower = list.get(position); followerName.setText(follower.ContactName); deleteButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Callback<ResponseBody> deleteFollowerListener = new Callback<ResponseBody>() { @Override public void onResponse(Response<ResponseBody> response, Retrofit retrofit) { if (response.isSuccess()) { Toast.makeText(context, "Follower deleted succesfully", Toast.LENGTH_LONG).show(); list.remove(position); notifyDataSetChanged(); } else { Toast.makeText(context, "Failed to delete follower", Toast.LENGTH_LONG).show(); } } @Override public void onFailure(Throwable t) { Toast.makeText(context, "Failed to delete follower", Toast.LENGTH_LONG).show(); } }; shareRest.deleteContact(follower.ContactId, deleteFollowerListener); } }); return view; }
@Override public Converter<ResponseBody, ?> fromResponseBody(Type type, Annotation[] annotations) { if (String.class.equals(type)) { return new Converter<ResponseBody, String>() { @Override public String convert(ResponseBody value) throws IOException { return value.string(); } }; } return null; }
private void handleRes(ResponseBody r) { try { System.out.println(r.string()); } catch (IOException e) { e.printStackTrace(); } }