List of usage examples for com.squareup.okhttp Response code
int code
To view the source code for com.squareup.okhttp Response code.
Click Source Link
From source file:co.paralleluniverse.fibers.okhttp.CallTest.java
License:Open Source License
private void postBodyRetransmittedAfterAuthorizationFail(String body) throws Exception { server.enqueue(new MockResponse().setResponseCode(401)); server.enqueue(new MockResponse()); Request request = new Request.Builder().url(server.getUrl("/")) .method("POST", RequestBody.create(null, body)).build(); String credential = Credentials.basic("jesse", "secret"); client.setAuthenticator(new RecordingOkAuthenticator(credential)); Response response = FiberOkHttpTestUtil.executeInFiberRecorded(client, request).response; assertEquals(200, response.code()); RecordedRequest recordedRequest1 = server.takeRequest(); assertEquals("POST", recordedRequest1.getMethod()); assertEquals(body, recordedRequest1.getBody().readUtf8()); assertNull(recordedRequest1.getHeader("Authorization")); RecordedRequest recordedRequest2 = server.takeRequest(); assertEquals("POST", recordedRequest2.getMethod()); assertEquals(body, recordedRequest2.getBody().readUtf8()); assertEquals(credential, recordedRequest2.getHeader("Authorization")); }
From source file:co.paralleluniverse.fibers.okhttp.CallTest.java
License:Open Source License
@Test public void reusedSinksGetIndependentTimeoutInstances() throws Exception { server.enqueue(new MockResponse()); server.enqueue(new MockResponse()); // Call 1: set a deadline on the request body. RequestBody requestBody1 = new RequestBody() { @Override/*from w ww . ja v a 2s.c om*/ public MediaType contentType() { return MediaType.parse("text/plain"); } @Override public void writeTo(BufferedSink sink) throws IOException { sink.writeUtf8("abc"); sink.timeout().deadline(5, TimeUnit.SECONDS); } }; Request request1 = new Request.Builder().url(server.getUrl("/")).method("POST", requestBody1).build(); Response response1 = FiberOkHttpUtil.executeInFiber(client, request1); assertEquals(200, response1.code()); // Call 2: check for the absence of a deadline on the request body. RequestBody requestBody2 = new RequestBody() { @Override public MediaType contentType() { return MediaType.parse("text/plain"); } @Override public void writeTo(BufferedSink sink) throws IOException { assertFalse(sink.timeout().hasDeadline()); sink.writeUtf8("def"); } }; Request request2 = new Request.Builder().url(server.getUrl("/")).method("POST", requestBody2).build(); Response response2 = FiberOkHttpUtil.executeInFiber(client, request2); assertEquals(200, response2.code()); // Use sequence numbers to confirm the connection was pooled. assertEquals(0, server.takeRequest().getSequenceNumber()); assertEquals(1, server.takeRequest().getSequenceNumber()); }
From source file:co.paralleluniverse.fibers.okhttp.CallTest.java
License:Open Source License
@Test public void setFollowSslRedirectsFalse() throws Exception { server.get().useHttps(sslContext.getSocketFactory(), false); server.enqueue(new MockResponse().setResponseCode(301).addHeader("Location: http://square.com")); client.setFollowSslRedirects(false); client.setSslSocketFactory(sslContext.getSocketFactory()); client.setHostnameVerifier(new RecordingHostnameVerifier()); Request request = new Request.Builder().url(server.getUrl("/")).build(); Response response = FiberOkHttpUtil.executeInFiber(client, request); assertEquals(301, response.code()); }
From source file:co.paralleluniverse.fibers.okhttp.CallTest.java
License:Open Source License
@Test public void asyncResponseCanBeConsumedLater() throws Exception { server.enqueue(new MockResponse().setBody("abc")); server.enqueue(new MockResponse().setBody("def")); Request request = new Request.Builder().url(server.getUrl("/")).header("User-Agent", "SyncApiTest").build(); final BlockingQueue<Response> responseRef = new SynchronousQueue<>(); client.newCall(request).enqueue(new Callback() { @Override/*from w ww.j a v a 2s . c om*/ public void onFailure(Request request, IOException e) { throw new AssertionError(); } @Override public void onResponse(Response response) throws IOException { try { responseRef.put(response); } catch (InterruptedException e) { throw new AssertionError(); } } }); Response response = responseRef.take(); assertEquals(200, response.code()); assertEquals("abc", response.body().string()); // Make another request just to confirm that that connection can be reused... FiberOkHttpTestUtil.executeInFiberRecorded(client, new Request.Builder().url(server.getUrl("/")).build()) .assertBody("def"); assertEquals(0, server.takeRequest().getSequenceNumber()); // New connection. assertEquals(1, server.takeRequest().getSequenceNumber()); // Connection reused. // ... even before we close the response body! response.body().close(); }
From source file:com.abiquo.apiclient.RestClient.java
License:Apache License
private void checkResponse(final Request request, final Response response, final String responseBody) throws IOException { int responseCode = response.code(); if (responseCode == 401 || responseCode == 403) { throw new AuthorizationException(responseCode, response.message()); } else if (responseCode >= 400) { if (responseBody == null) { throw new HttpException(responseCode, response.message()); }//w w w. j a v a2 s .c o m try { ErrorsDto errors = json.read(responseBody, ErrorsDto.class); throw new AbiquoException(responseCode, errors); } catch (Exception ex) { Throwables.propagateIfInstanceOf(ex, AbiquoException.class); throw new HttpException(responseCode, response.message() + ". Body: " + responseBody); } } }
From source file:com.aix.city.comm.OkHttpStack.java
License:Open Source License
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { OkHttpClient client = mClient.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)); }/*from w w w .j a v a2 s. co m*/ 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; }
From source file:com.andrew67.ddrfinder.adapters.MapLoaderV1.java
License:Open Source License
@Override protected ApiResult doInBackground(LatLngBounds... boxes) { // Fetch machine data in JSON format JSONArray jArray = new JSONArray(); try {/* w w w .j a va 2 s .c o m*/ if (boxes.length == 0) throw new IllegalArgumentException("No boxes passed to doInBackground"); final LatLngBounds box = boxes[0]; final OkHttpClient client = new OkHttpClient(); final String LOADER_API_URL = sharedPref.getString(SettingsActivity.KEY_PREF_API_URL, ""); final HttpUrl requestURL = HttpUrl.parse(LOADER_API_URL).newBuilder() .addQueryParameter("source", "android") .addQueryParameter("latupper", "" + box.northeast.latitude) .addQueryParameter("longupper", "" + box.northeast.longitude) .addQueryParameter("latlower", "" + box.southwest.latitude) .addQueryParameter("longlower", "" + box.southwest.longitude).build(); Log.d("api", "Request URL: " + requestURL); final Request get = new Request.Builder().header("User-Agent", BuildConfig.APPLICATION_ID + " " + BuildConfig.VERSION_NAME + "/Android?SDK=" + Build.VERSION.SDK_INT).url(requestURL).build(); final Response response = client.newCall(get).execute(); final int statusCode = response.code(); Log.d("api", "Status code: " + statusCode); // Data loaded OK if (statusCode == 200) { final String jResponse = response.body().string(); Log.d("api", "Raw API result: " + jResponse); jArray = new JSONArray(jResponse); } // Code used for invalid parameters; in this case exceeding // the limits of the boundary box else if (statusCode == 400) { return new ApiResultV1(ApiResultV1.ERROR_ZOOM); } // Unexpected error code else { return new ApiResultV1(ApiResultV1.ERROR_API); } } catch (Exception e) { e.printStackTrace(); } // Return list ArrayList<ArcadeLocation> out = new ArrayList<>(); try { for (int i = 0; i < jArray.length(); ++i) { final JSONObject obj = (JSONObject) jArray.get(i); final String name = obj.getString("name"); boolean closed = false; if (ArcadeLocation.CLOSED.matcher(name).matches()) { closed = true; } // Fields added after ddr-finder 1.0 API should be // explicitly tested for, in order to maintain // compatibility with deployments of older versions boolean hasDDR = false; if (obj.has("hasDDR") && obj.getInt("hasDDR") == 1) { hasDDR = true; } out.add(new ArcadeLocationV1(obj.getInt("id"), name, obj.getString("city"), new LatLng(obj.getDouble("latitude"), obj.getDouble("longitude")), hasDDR, closed)); } } catch (Exception e) { out.clear(); } return new ApiResultV1(out, boxes[0]); }
From source file:com.andrew67.ddrfinder.adapters.MapLoaderV3.java
License:Open Source License
@Override protected ApiResult doInBackground(LatLngBounds... boxes) { ApiResult result = null;/* w w w .j a v a2 s . c o m*/ try { if (boxes.length == 0) throw new IllegalArgumentException("No boxes passed to doInBackground"); final LatLngBounds box = boxes[0]; String datasrc = sharedPref.getString(SettingsActivity.KEY_PREF_API_SRC, ""); if (SettingsActivity.API_SRC_CUSTOM.equals(datasrc)) { datasrc = sharedPref.getString(SettingsActivity.KEY_PREF_API_SRC_CUSTOM, ""); } final OkHttpClient client = new OkHttpClient(); final String LOADER_API_URL = sharedPref.getString(SettingsActivity.KEY_PREF_API_URL, ""); final HttpUrl requestURL = HttpUrl.parse(LOADER_API_URL).newBuilder() .addQueryParameter("version", "" + SettingsActivity.API_V30) .addQueryParameter("datasrc", datasrc) .addQueryParameter("latupper", "" + box.northeast.latitude) .addQueryParameter("lngupper", "" + box.northeast.longitude) .addQueryParameter("latlower", "" + box.southwest.latitude) .addQueryParameter("lnglower", "" + box.southwest.longitude).build(); Log.d("api", "Request URL: " + requestURL); final Request get = new Request.Builder().header("User-Agent", BuildConfig.APPLICATION_ID + " " + BuildConfig.VERSION_NAME + "/Android?SDK=" + Build.VERSION.SDK_INT).url(requestURL).build(); final Response response = client.newCall(get).execute(); final int statusCode = response.code(); Log.d("api", "Status code: " + statusCode); // Data/error loaded OK if (statusCode == 200 || statusCode == 400) { final Gson gson = new Gson(); result = gson.fromJson(response.body().charStream(), Result.class); result.setBounds(box); Log.d("api", "Raw API result: " + gson.toJson(result, Result.class)); } // Unexpected error code else { throw new RuntimeException("Unexpected HTTP status code: " + statusCode); } } catch (Exception e) { e.printStackTrace(); } return result; }
From source file:com.android.cloudfiles.cloudfilesforandroid.CloudFiles.java
License:Apache License
private String upload(InputStream inputStream, final long size, String region, String bucket, String key) throws IOException { CountingFileRequestBody body = new CountingFileRequestBody(inputStream, size, "", new CountingFileRequestBody.ProgressListener() { @Override/*www . ja va 2s.c o m*/ public void percentageTransferred(int percentage) { System.err.println(percentage); } }); Request request = new Request.Builder().url(urls.get(region) + "/" + bucket + "/" + key) .header("X-Auth-Token", getToken()).addHeader("Content-Length", String.valueOf(size)).put(body) .build(); Response response = client.newCall(request).execute(); if (response.code() == 404) { createBucket(region, bucket); return upload(inputStream, size, region, bucket, key); } return getBucketCdnUrl(region, bucket) + "/" + key; }
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();/* www .ja va 2 s . com*/ } 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(); } }); }