com.squareup.okhttp.CacheControl#com.squareup.okhttp.Call源码实例Demo

下面列出了com.squareup.okhttp.CacheControl#com.squareup.okhttp.Call 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: NewsMe   文件: RequestCall.java
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;
}
 
源代码2 项目: httplite   文件: Ok2Lite.java
@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);
}
 
源代码3 项目: ariADDna   文件: ApiClient.java
/**
 * 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);
    }
}
 
源代码4 项目: JianDan_OkHttp   文件: OkHttpProxy.java
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;
    }
 
源代码5 项目: zsync4j   文件: HttpClientTest.java
@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());
  }
}
 
源代码6 项目: zsync4j   文件: HttpClientTest.java
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;
}
 
源代码7 项目: zsync4j   文件: HttpClientTest.java
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);
      }
    }
  };
}
 
@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);
    }
}
 
源代码9 项目: lams   文件: OkHttpAsyncClientHttpRequest.java
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);
		}
	});
}
 
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);
      }
     });
 }
 
/**
 * 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);
  }
}
 
源代码12 项目: lunzi   文件: UploadFileRequest.java
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);
}
 
源代码13 项目: meiShi   文件: OkHttpDownloadRequest.java
@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);
}
 
源代码14 项目: JianDan_OkHttp   文件: OkHttpProxy.java
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;
}
 
源代码15 项目: components   文件: HadoopCMConfigurator.java
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());
}
 
源代码16 项目: zsync4j   文件: HttpClientTest.java
@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());
    }
  }

}
 
源代码17 项目: zsync4j   文件: HttpClientTest.java
@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());
}
 
源代码18 项目: zsync4j   文件: HttpClientTest.java
@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);
    }
  };
}
 
源代码19 项目: NewsMe   文件: RequestCall.java
public Call getCall()
{
    return call;
}
 
源代码20 项目: nifi-api-client-java   文件: ApiClient.java
/**
 * 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);
}
 
源代码21 项目: httplite   文件: Ok2Lite.java
@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);
}
 
源代码22 项目: httplite   文件: Ok2Lite.java
private CallHandle(Call call) {
    this.call = call;
}
 
源代码23 项目: ariADDna   文件: ApiClient.java
/**
 * 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);
}
 
源代码24 项目: JianDan_OkHttp   文件: OkHttpProxy.java
public static Call get(String url, OkHttpCallback responseCallback) {
    return get(url, null, responseCallback);
}
 
源代码25 项目: JianDan_OkHttp   文件: OkHttpProxy.java
public static Call post(String url, Map<String, String> params, OkHttpCallback responseCallback) {
    return post(url, params, null, responseCallback);
}
 
源代码26 项目: zsync4j   文件: HttpClientTest.java
Function<Request, Call> challengeSequence(final URI uri, final Map<String, Credentials> credentials) {
  return sequence(newUnauthorizedRequestCall(uri), newAuthorizedRequestCall(uri, credentials));
}
 
源代码27 项目: zsync4j   文件: HttpClientTest.java
public void setNewCall(Function<? super Request, ? extends Call> newCall) {
  this.newCall = newCall;
}
 
源代码28 项目: zsync4j   文件: HttpClientTest.java
@Override
public Call newCall(Request request) {
  return this.newCall.apply(request);
}
 
源代码29 项目: knox   文件: ClouderaManagerServiceDiscoveryTest.java
@Override
public <T> ApiResponse<T> execute(Call call, Type returnType) throws ApiException {
  return (ApiResponse<T>) responseMap.get(returnType);
}
 
源代码30 项目: flickr-uploader   文件: RPC.java
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;
}