com.squareup.okhttp.Call Java Examples
The following examples show how to use
com.squareup.okhttp.Call.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RequestCall.java From NewsMe with Apache License 2.0 | 6 votes |
public Call generateCall(Callback callback) { request = generateRequest(callback); if (readTimeOut > 0 || writeTimeOut > 0 || connTimeOut > 0) { cloneClient(); readTimeOut = readTimeOut > 0 ? readTimeOut : OkHttpUtils.DEFAULT_MILLISECONDS; writeTimeOut = writeTimeOut > 0 ? writeTimeOut : OkHttpUtils.DEFAULT_MILLISECONDS; connTimeOut = connTimeOut > 0 ? connTimeOut : OkHttpUtils.DEFAULT_MILLISECONDS; clone.setReadTimeout(readTimeOut, TimeUnit.MILLISECONDS); clone.setWriteTimeout(writeTimeOut, TimeUnit.MILLISECONDS); clone.setConnectTimeout(connTimeOut, TimeUnit.MILLISECONDS); call = clone.newCall(request); } else { call = OkHttpUtils.getInstance().getOkHttpClient().newCall(request); } return call; }
Example #2
Source File: HttpClientTest.java From zsync4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
Function<Request, Call> newAuthorizedRequestCall(final URI uri, final Map<String, Credentials> credentials) { return new Function<Request, Call>() { @Override public Call apply(Request request) { assertEquals(uri.toString(), request.urlString()); assertEquals("GET", request.method()); assertEquals(credentials.get(uri.getHost()).basic(), request.header("Authorization")); try { ResponseBody body = mock(ResponseBody.class); when(body.source()).thenReturn(mock(BufferedSource.class)); when(body.byteStream()).thenReturn(mock(InputStream.class)); final Response response = new Response.Builder().code(HTTP_OK).body(body).request(request).protocol(HTTP_1_1).build(); final Call call = mock(Call.class); when(call.execute()).thenReturn(response); return call; } catch (IOException e) { throw new RuntimeException(e); } } }; }
Example #3
Source File: HttpClientTest.java From zsync4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
Function<Request, Call> newUnauthorizedRequestCall(final URI uri) { final Function<Request, Call> noAuthRequest = new Function<Request, Call>() { @Override public Call apply(Request request) { assertEquals(uri.toString(), request.urlString()); assertEquals("GET", request.method()); assertNull(request.header("Authorization")); final Response response = new Response.Builder().header("WWW-Authenticate", "BASIC realm=\"global\"").code(HTTP_UNAUTHORIZED) .request(request).protocol(HTTP_1_1).build(); Call call = mock(Call.class); try { when(call.execute()).thenReturn(response); } catch (IOException e) { throw new RuntimeException(e); } return call; } }; return noAuthRequest; }
Example #4
Source File: HttpClientTest.java From zsync4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
@SuppressWarnings("unchecked") @Test public void runtimeExceptionThrownForIoExceptionDuringHttpCommunication() throws Exception { // Arrange OkHttpClient mockHttpClient = mock(OkHttpClient.class); RangeReceiver mockReceiver = mock(RangeReceiver.class); RangeTransferListener listener = mock(RangeTransferListener.class); when(listener.newTransfer(any(List.class))).thenReturn(mock(HttpTransferListener.class)); List<ContentRange> ranges = this.createSomeRanges(1); URI url = new URI("http://host/someurl"); IOException expected = new IOException("IO"); Call mockCall = mock(Call.class); when(mockCall.execute()).thenThrow(expected); when(mockHttpClient.newCall(any(Request.class))).thenReturn(mockCall); // Act try { new HttpClient(mockHttpClient).partialGet(url, ranges, Collections.<String, Credentials>emptyMap(), mockReceiver, listener); } catch (IOException exception) { // Assert assertEquals("IO", exception.getMessage()); } }
Example #5
Source File: OkHttpProxy.java From JianDan_OkHttp with Apache License 2.0 | 6 votes |
public static Call post(String url, Map<String, String> params, Object tag, OkHttpCallback responseCallback) { Request.Builder builder = new Request.Builder().url(url); if (tag != null) { builder.tag(tag); } FormEncodingBuilder encodingBuilder = new FormEncodingBuilder(); if (params != null && params.size() > 0) { for (String key : params.keySet()) { encodingBuilder.add(key, params.get(key)); } } RequestBody formBody = encodingBuilder.build(); builder.post(formBody); Request request = builder.build(); Call call = getInstance().newCall(request); call.enqueue(responseCallback); return call; }
Example #6
Source File: Ok2Lite.java From httplite with Apache License 2.0 | 6 votes |
@Override public void enqueue(final Request request,final Callback<Response> callback) { Call call = mClient.newCall(makeRequest(request)); request.handle().setHandle(new CallHandle(call)); com.squareup.okhttp.Callback ok2Callback = new com.squareup.okhttp.Callback() { @Override public void onFailure(com.squareup.okhttp.Request okReq, IOException e) { Exception throwable; if("Canceled".equals(e.getMessage())){ throwable = new CanceledException(e); }else{ throwable = e; } callback.onFailed(request,throwable); } @Override public void onResponse(com.squareup.okhttp.Response response) throws IOException { callback.onSuccess(request,response.headers().toMultimap(),new OkResponse(response,request)); } }; call.enqueue(ok2Callback); }
Example #7
Source File: ApiClient.java From ariADDna with Apache License 2.0 | 6 votes |
/** * 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(); LOGGER.info("Method {execute} was called, with params isExecuted: {}, returnType: {}", call.isExecuted(), returnType == null ? null : returnType.getTypeName()); T data = handleResponse(response, returnType); return new ApiResponse<T>(response.code(), response.headers().toMultimap(), data); } catch (IOException e) { LOGGER.error("Method {execute} was called, with params :{},{}", call.isExecuted(), returnType == null ? null : returnType.getTypeName()); LOGGER.error("Method {execute} throw exception: " + e); throw new ApiException(e); } }
Example #8
Source File: OkHttpAsyncClientHttpRequest.java From lams with GNU General Public License v2.0 | 5 votes |
public OkHttpListenableFuture(Call call) { this.call = call; this.call.enqueue(new Callback() { @Override public void onResponse(Response response) { set(new OkHttpClientHttpResponse(response)); } @Override public void onFailure(Request request, IOException ex) { setException(ex); } }); }
Example #9
Source File: HttpClientTest.java From zsync4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@SafeVarargs final Function<Request, Call> sequence(final Function<Request, Call>... calls) { return new Function<Request, Call>() { int i = 0; @Override public Call apply(Request input) { return calls[this.i++].apply(input); } }; }
Example #10
Source File: HttpClientTest.java From zsync4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test public void testTransferListener() throws IOException, HttpError { final URI uri = URI.create("http://host/bla"); final byte[] data = new byte[17]; final ResponseBody body = mock(ResponseBody.class); when(body.contentLength()).thenReturn((long) data.length); when(body.source()).thenReturn(mock(BufferedSource.class)); final InputStream inputStream = new ByteArrayInputStream(data); when(body.byteStream()).thenReturn(inputStream); final Request request = new Request.Builder().url(uri.toString()).build(); final Response response = new Response.Builder().protocol(HTTP_1_1).body(body).request(request).code(200).build(); final Call mockCall = mock(Call.class); when(mockCall.execute()).thenReturn(response); final OkHttpClient mockHttpClient = mock(OkHttpClient.class); when(mockHttpClient.newCall(any(Request.class))).thenReturn(mockCall); final EventLogHttpTransferListener listener = new EventLogHttpTransferListener(); final InputStream in = new HttpClient(mockHttpClient).get(uri, Collections.<String, Credentials>emptyMap(), listener); final byte[] b = new byte[8]; assertEquals(0, in.read()); assertEquals(8, in.read(b)); assertEquals(8, in.read(b, 0, 8)); assertEquals(-1, in.read()); in.close(); final List<Event> events = ImmutableList.of(new Initialized(new Request.Builder().url(uri.toString()).build()), new Started(uri, data.length), new Transferred(1), new Transferred(8), new Transferred(8), Closed.INSTANCE); assertEquals(events, listener.getEventLog()); }
Example #11
Source File: HttpClientTest.java From zsync4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@SuppressWarnings("unchecked") @Test public void runtimeExceptionThrownForHttpResponsesOtherThan206() throws IOException, URISyntaxException { // Arrange List<Integer> responsesToTest = Lists.newArrayList(500, 413); // Add whatever other ones we want OkHttpClient mockHttpClient = mock(OkHttpClient.class); RangeReceiver mockReceiver = mock(RangeReceiver.class); RangeTransferListener listener = mock(RangeTransferListener.class); when(listener.newTransfer(any(List.class))).thenReturn(mock(HttpTransferListener.class)); List<ContentRange> ranges = this.createSomeRanges(1); URI url = new URI("http://host/someurl"); for (Integer responseToTest : responsesToTest) { // Arrange some more Call mockCall = mock(Call.class); Response fakeResponse = this.fakeResponse(responseToTest); when(mockHttpClient.newCall(any(Request.class))).thenReturn(mockCall); when(mockCall.execute()).thenReturn(fakeResponse); // Act try { new HttpClient(mockHttpClient).partialGet(url, ranges, Collections.<String, Credentials>emptyMap(), mockReceiver, listener); } catch (HttpError exception) { assertEquals(responseToTest.intValue(), exception.getCode()); } } }
Example #12
Source File: HadoopCMConfigurator.java From components with Apache License 2.0 | 5 votes |
private void setAPIVersion(ApiClient client) throws ApiException { String requestPath = "/version"; String method = "GET"; Map<String, String> headerParams = new HashMap<String, String>(); String[] accepts = { "application/json" }; String accept = client.selectHeaderAccept(accepts); if (accept != null) headerParams.put("Accept", accept); String[] contentTypes = new String[0]; String[] authNames = { "basic" }; String contentType = client.selectHeaderContentType(contentTypes); headerParams.put("Content-Type", contentType); Call c = client.buildCall(requestPath, method, null, null, headerParams, null, authNames, null); Type returnType = (new TypeToken<String>() { }).getType(); ApiResponse<String> version = client.execute(c, returnType); if (version.getStatusCode() == 200) { // highest version client.setBasePath(client.getBasePath() + "/" + version.getData()); } else if (version.getStatusCode() == 404) { // default version client.setBasePath(client.getBasePath() + "/" + DEFAULT_API_VERSION); } else { // throw exception throw new RuntimeException("Can't retrieve api version from " + client.getBasePath()); } log.log(Level.INFO, "setAPIVersion, base path: " + client.getBasePath()); }
Example #13
Source File: OkHttpProxy.java From JianDan_OkHttp with Apache License 2.0 | 5 votes |
public static Call get(String url, Object tag, OkHttpCallback responseCallback) { Request.Builder builder = new Request.Builder().url(url); if (tag != null) { builder.tag(tag); } Request request = builder.build(); Call call = getInstance().newCall(request); call.enqueue(responseCallback); return call; }
Example #14
Source File: OkHttpDownloadRequest.java From meiShi with Apache License 2.0 | 5 votes |
@Override public <T> T invoke(Class<T> clazz) throws IOException { final Call call = mOkHttpClient.newCall(request); Response response = call.execute(); return (T) saveFile(response, null); }
Example #15
Source File: UploadFileRequest.java From lunzi with Apache License 2.0 | 5 votes |
private void newRequestCall(Callback callback, String url, RequestBody requestBody) { Request request = new Request.Builder() .url(url) .post(requestBody) .build(); Call call = mOkHttpClient.newCall(request); call.enqueue(callback); }
Example #16
Source File: OkHttpNetworkFetchProducer.java From FanXin-based-HuanXin with GNU General Public License v2.0 | 5 votes |
/** * Handles IOExceptions. * * <p> OkHttp notifies callers of cancellations via an IOException. If IOException is caught * after request cancellation, then the exception is interpreted as successful cancellation * and onCancellation is called. Otherwise onFailure is called. */ private void handleException( final Call call, final NfpRequestState requestState, final IOException ioe) { if (call.isCanceled()) { onCancellation(requestState, null); } else { onFailure(requestState, ioe, null); } }
Example #17
Source File: OkHttpClientHttpRequest.java From spring4-understanding with Apache License 2.0 | 5 votes |
public OkHttpListenableFuture(Call call) { this.call = call; this.call.enqueue(new Callback() { @Override public void onResponse(Response response) { set(new OkHttpClientHttpResponse(response)); } @Override public void onFailure(Request request, IOException ex) { setException(ex); } }); }
Example #18
Source File: OkHttpClientAsyncInstrumentation.java From apm-agent-java with Apache License 2.0 | 5 votes |
@Advice.OnMethodEnter(suppress = Throwable.class) private static void onBeforeEnqueue(@Advice.Origin Class<? extends Call> clazz, @Advice.FieldValue(value = "originalRequest", typing = Assigner.Typing.DYNAMIC, readOnly = false) @Nullable Request originalRequest, @Advice.Argument(value = 0, readOnly = false) @Nullable Callback callback, @Advice.Local("span") Span span) { if (tracer == null || tracer.getActive() == null || callbackWrapperCreator == null) { return; } final WrapperCreator<Callback> wrapperCreator = callbackWrapperCreator.getForClassLoaderOfClass(clazz); if (originalRequest == null || callback == null || wrapperCreator == null) { return; } final AbstractSpan<?> parent = tracer.getActive(); Request request = originalRequest; URL url = request.url(); span = HttpClientHelper.startHttpClientSpan(parent, request.method(), url.toString(), url.getProtocol(), OkHttpClientHelper.computeHostName(url.getHost()), url.getPort()); if (span != null) { span.activate(); if (headerSetterHelperManager != null) { TextHeaderSetter<Request.Builder> headerSetter = headerSetterHelperManager.getForClassLoaderOfClass(Request.class); if (headerSetter != null) { Request.Builder builder = originalRequest.newBuilder(); span.propagateTraceContext(builder, headerSetter); originalRequest = builder.build(); } } callback = wrapperCreator.wrap(callback, span); } }
Example #19
Source File: RPC.java From flickr-uploader with GNU General Public License v2.0 | 4 votes |
private static String postRpc(Method method, Object[] args) { String responseStr = null; boolean retry = true; int executionCount = 0; while (retry) { try { if (executionCount > 0) { Thread.sleep(RETRY_SLEEP_TIME_MILLIS * executionCount); } executionCount++; Request.Builder builder = new Request.Builder().url(Config.HTTP_START + "/androidRpc?method=" + method.getName()); if (args != null) { // String encode = ToolStream.encode(args); // LOG.debug("encoded string : " + encode.length()); // LOG.debug("gzipped string : " + ToolStream.encodeGzip(args).length()); Object[] args_logs = new Object[3]; args_logs[0] = args; builder.post(RequestBody.create(MediaType.parse("*/*"), Streams.encodeGzip(args_logs))); } else { builder.post(RequestBody.create(MediaType.parse("*/*"), "")); } LOG.info("postRpc " + method.getName() + "(" + Joiner.on(',').useForNull("null").join(args) + ")"); Request request = builder.build(); Call call = client.newCall(request); Response response = call.execute(); responseStr = response.body().string(); retry = false; } catch (Throwable e) { LOG.error("Failed androidRpc (" + e.getClass().getCanonicalName() + ") executionCount=" + executionCount + " : " + method.getName() + " : " + Arrays.toString(args)); if (e instanceof InterruptedIOException || e instanceof SSLHandshakeException) { retry = false; } else if (executionCount >= DEFAULT_MAX_RETRIES) { retry = false; } if (e instanceof UnknownHostException || e instanceof SocketException) { notifyNetworkError(); } } } return responseStr; }
Example #20
Source File: ClouderaManagerServiceDiscoveryTest.java From knox with Apache License 2.0 | 4 votes |
@Override public <T> ApiResponse<T> execute(Call call, Type returnType) throws ApiException { return (ApiResponse<T>) responseMap.get(returnType); }
Example #21
Source File: OkHttpProxy.java From JianDan_OkHttp with Apache License 2.0 | 4 votes |
public static Call get(String url, OkHttpCallback responseCallback) { return get(url, null, responseCallback); }
Example #22
Source File: Ok2Lite.java From httplite with Apache License 2.0 | 4 votes |
private CallHandle(Call call) { this.call = call; }
Example #23
Source File: OkHttpProxy.java From JianDan_OkHttp with Apache License 2.0 | 4 votes |
public static Call post(String url, Map<String, String> params, OkHttpCallback responseCallback) { return post(url, params, null, responseCallback); }
Example #24
Source File: Ok2Lite.java From httplite with Apache License 2.0 | 4 votes |
@Override public Response execute(Request request) throws Exception { Call call = mClient.newCall(makeRequest(request)); request.handle().setHandle(new CallHandle(call)); return new OkResponse(call.execute(),request); }
Example #25
Source File: ApiClient.java From nifi-api-client-java with Apache License 2.0 | 4 votes |
/** * Build HTTP call with the given options. * * @param path The sub-path of the HTTP URL * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" * @param queryParams The query parameters * @param body The request body object * @param headerParams The header parameters * @param formParams The form parameters * @param authNames The authentications to apply * @param progressRequestListener Progress request listener * @return The HTTP call * @throws ApiException If fail to serialize the request body object */ public Call buildCall(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { updateParamsForAuth(authNames, queryParams, headerParams); final String url = buildUrl(path, queryParams); final Request.Builder reqBuilder = new Request.Builder().url(url); processHeaderParams(headerParams, reqBuilder); String contentType = (String) headerParams.get("Content-Type"); // ensuring a default content type if (contentType == null) { contentType = "application/json"; } RequestBody reqBody; if (!HttpMethod.permitsRequestBody(method)) { reqBody = null; } else if ("application/x-www-form-urlencoded".equals(contentType)) { reqBody = buildRequestBodyFormEncoding(formParams); } else if ("multipart/form-data".equals(contentType)) { reqBody = buildRequestBodyMultipart(formParams); } else if (body == null) { if ("DELETE".equals(method)) { // allow calling DELETE without sending a request body reqBody = null; } else { // use an empty request body (for POST, PUT and PATCH) reqBody = RequestBody.create(MediaType.parse(contentType), ""); } } else { reqBody = serialize(body, contentType); } Request request = null; if(progressRequestListener != null && reqBody != null) { ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener); request = reqBuilder.method(method, progressRequestBody).build(); } else { request = reqBuilder.method(method, reqBody).build(); } return httpClient.newCall(request); }
Example #26
Source File: ApiClient.java From ariADDna with Apache License 2.0 | 4 votes |
/** * Build HTTP call with the given options. * * @param path The sub-path of the HTTP URL * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" * @param queryParams The query parameters * @param body The request body object * @param headerParams The header parameters * @param formParams The form parameters * @param authNames The authentications to apply * @param progressRequestListener Progress request listener * @return The HTTP call * @throws ApiException If fail to serialize the request body object */ public Call buildCall(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { updateParamsForAuth(authNames, queryParams, headerParams); final String url = buildUrl(path, queryParams); final Request.Builder reqBuilder = new Request.Builder().url(url); processHeaderParams(headerParams, reqBuilder); String contentType = (String) headerParams.get("Content-Type"); // ensuring a default content type if (contentType == null) { contentType = "application/json"; } RequestBody reqBody; if (!HttpMethod.permitsRequestBody(method)) { reqBody = null; } else if ("application/x-www-form-urlencoded".equals(contentType)) { reqBody = buildRequestBodyFormEncoding(formParams); } else if ("multipart/form-data".equals(contentType)) { reqBody = buildRequestBodyMultipart(formParams); } else if (body == null) { if ("DELETE".equals(method)) { // allow calling DELETE without sending a request body reqBody = null; } else { // use an empty request body (for POST, PUT and PATCH) reqBody = RequestBody.create(MediaType.parse(contentType), ""); } } else { reqBody = serialize(body, contentType); } Request request = null; if (progressRequestListener != null && reqBody != null) { ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener); request = reqBuilder.method(method, progressRequestBody).build(); } else { request = reqBuilder.method(method, reqBody).build(); } return httpClient.newCall(request); }
Example #27
Source File: HttpClientTest.java From zsync4j with BSD 3-Clause "New" or "Revised" License | 4 votes |
@Override public Call newCall(Request request) { return this.newCall.apply(request); }
Example #28
Source File: RequestCall.java From NewsMe with Apache License 2.0 | 4 votes |
public Call getCall() { return call; }
Example #29
Source File: HttpClientTest.java From zsync4j with BSD 3-Clause "New" or "Revised" License | 4 votes |
Function<Request, Call> challengeSequence(final URI uri, final Map<String, Credentials> credentials) { return sequence(newUnauthorizedRequestCall(uri), newAuthorizedRequestCall(uri, credentials)); }
Example #30
Source File: HttpClientTest.java From zsync4j with BSD 3-Clause "New" or "Revised" License | 4 votes |
public void setNewCall(Function<? super Request, ? extends Call> newCall) { this.newCall = newCall; }