public com.squareup.okhttp.Call listAsync(String namespace, String pretty, String _continue, String fieldSelector, Boolean includeUninitialized, String labelSelector, Integer limit, String resourceVersion, Integer timeoutSeconds, Boolean watch, final ApiCallback<ARList<T>> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = listValidateBeforeCall(namespace, pretty, _continue, fieldSelector, includeUninitialized, labelSelector, limit, resourceVersion, timeoutSeconds, watch, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<ARList<T>>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; }
@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")); }
Call post(Callback callback) throws IOException { OkHttpClient client = getUnsafeOkHttpClient(); CookieManager cookieManager = new CookieManager(); cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); client.setCookieHandler(cookieManager); RequestBody requestBody = new FormEncodingBuilder() .add("user_id", NetId) .add("user_password", password) .build(); Request request = new Request.Builder() .url("https://studentmaintenance.webapps.snu.edu.in/students/public/studentslist/studentslist/loginauth") .post(requestBody) .build(); Call call = client.newCall(request); call.enqueue(callback); return call; }
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; }
@Override public Call newRequestToken(String callback) { Request req = new Request.Builder() .url(provider.requestTokenUrl()) .method(provider.requestTokenVerb(), new FormEncodingBuilder().build()) .header("X-OKHttp-OAuth-Authorized", "yes") .build(); OAuthRequest orq = new OAuthRequest(req); try { OAuthRequest authReq = service.authorizeRequest(orq, consumer, null); return okHttpClient.newCall(authReq.authorizedRequest()); } catch (SigningException e) { e.printStackTrace(); // TODO what to do now?!? } return null; }
@Override public Call newAccessToken(String verifier) { Request req = new Request.Builder() .url(provider.requestTokenUrl()) .method( provider.requestTokenVerb(), new FormEncodingBuilder() .add(OAuth.VERIFIER, verifier) .build() ) .build(); OAuthRequest orq = new OAuthRequest(req); try { OAuthRequest authReq = service.authorizeRequest(orq, consumer, null); return okHttpClient.newCall(authReq.authorizedRequest()); } catch (SigningException e) { e.printStackTrace(); // TODO what to do now?!? } return null; }
@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); }
/** * Send POST request to the server to log the user in or out. * * @param mode Mode is used by the server script to differentiate between login and logout. * 191: Login * 193: Logout * @param username The username of user * @param password The password of user * @param callback The Callback * @return Call object * @throws IOException */ Call post(String mode, String username, String password, Callback callback) throws IOException { OkHttpClient client = new OkHttpClient(); RequestBody formBody = new FormEncodingBuilder() .add("mode", mode) .add("username", username + "@snu.in") .add("password", password) .build(); Request request = new Request.Builder() .url("http://192.168.50.1/24online/servlet/E24onlineHTTPClient") .post(formBody) .build(); Call call = client.newCall(request); call.enqueue(callback); return call; }
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; }
@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()); } }
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; }
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); } } }; }
/** * Get current viewstack of the application * @param callback Callback for the request * @return ResponseFuture */ public Call getViewstack(final Callback callback) { RpcRequest request = new RpcRequest("getviewstack", RequestId.GET_VIEWSTACK); if(Version.compare(mVersion, ZERO_VERSION)) { return request(request, callback); } else { return request(request, new Callback() { @Override public void onCompleted(Exception e, RpcResponse result) { try { if (e == null && result != null && result.result != null) { if (result.result instanceof ArrayList) { ArrayList list = (ArrayList) result.result; LinkedTreeMap<String, Object> map = new LinkedTreeMap<String, Object>(); map.put("viewstack", list.get(0)); result.result = map; } } callback.onCompleted(e, result); } catch(Exception exception) { exception.printStackTrace(); } } }); } }
/** * Get available subtitles for the current playing or selected video * @param callback Callback for the request * @return ResponseFuture */ public Call getSubtitles(final Callback callback) { RpcRequest request = new RpcRequest("getsubtitles", RequestId.GET_SUBTITLES); if(Version.compare(mVersion, ZERO_VERSION)) { return request(request, callback); } else { return request(request, new Callback() { @Override public void onCompleted(Exception e, RpcResponse result) { if (e == null && result != null && result.result != null) { ArrayList list = (ArrayList) result.result; LinkedTreeMap<String, Object> map = new LinkedTreeMap<String, Object>(); map.put("subtitles", list.get(0)); result.result = map; } callback.onCompleted(e, result); } }); } }
/** * 同步的Get请求 * * @param url * @return Response */ private Response _getAsyn(String url) throws IOException { final Request request = new Request.Builder() .url(url) .build(); Call call = mOkHttpClient.newCall(request); Response execute = call.execute(); return execute; }
/** * Handles exceptions. * * <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 Exception e, final Callback callback) { if (call.isCanceled()) { callback.onCancellation(); } else { callback.onFailure(e); } }
Call post(String url, String json, Callback callback) { RequestBody body = RequestBody.create(JSON, json); Request request = new Request.Builder() .addHeader("Content-Type","application/json") .addHeader("Authorization","key=AIzaSyAkeFnKc_r6TJSO7tm5OVnzkbni6dEk4Lw") .url(url) .post(body) .build(); Call call = client.newCall(request); call.enqueue(callback); return call; }
/** * (asynchronously) * delete collection of CustomResourceDefinition * @param pretty If 'true', then the output is pretty printed. (optional) * @param _continue The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. (optional) * @param fieldSelector A selector to restrict the list of returned objects by their fields. Defaults to everything. (optional) * @param includeUninitialized If true, partially initialized resources are included in the response. (optional) * @param labelSelector A selector to restrict the list of returned objects by their labels. Defaults to everything. (optional) * @param limit limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. (optional) * @param resourceVersion When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. (optional) * @param timeoutSeconds Timeout for the list/watch call. (optional) * @param watch Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. (optional) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call deleteCollectionAsync(String namespace, String pretty, String _continue, String fieldSelector, Boolean includeUninitialized, String labelSelector, Integer limit, String resourceVersion, Integer timeoutSeconds, Boolean watch, final ApiCallback<V1Status> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = deleteCollectionValidateBeforeCall(namespace, pretty, _continue, fieldSelector, includeUninitialized, labelSelector, limit, resourceVersion, timeoutSeconds, watch, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<V1Status>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; }
/** * (asynchronously) * delete a CustomResourceDefinition * @param name name of the CustomResourceDefinition (required) * @param body (required) * @param pretty If 'true', then the output is pretty printed. (optional) * @param gracePeriodSeconds The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. (optional) * @param orphanDependents Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. (optional) * @param propagationPolicy Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. (optional) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call deleteAsync(String namespace, String name, V1DeleteOptions body, String pretty, Integer gracePeriodSeconds, Boolean orphanDependents, String propagationPolicy, final ApiCallback<V1Status> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = deleteValidateBeforeCall(namespace, name, body, pretty, gracePeriodSeconds, orphanDependents, propagationPolicy, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<V1Status>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; }
/** * (asynchronously) * partially update the specified CustomResourceDefinition * @param name name of the CustomResourceDefinition (required) * @param body (required) * @param pretty If 'true', then the output is pretty printed. (optional) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call patchAsync(String namespace, String name, Object body, String pretty, final ApiCallback<T> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = patchValidateBeforeCall(namespace, name, body, pretty, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<T>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; }
/** * (asynchronously) * read the specified CustomResourceDefinition * @param name name of the CustomResourceDefinition (required) * @param pretty If 'true', then the output is pretty printed. (optional) * @param exact Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'. (optional) * @param export Should this value be exported. Export strips fields that a user can not specify. (optional) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call readAsync(String namespace, String name, String pretty, Boolean exact, Boolean export, final ApiCallback<T> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = readValidateBeforeCall(namespace, name, pretty, exact, export, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<T>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; }
/** * (asynchronously) * replace the specified CustomResourceDefinition * @param name name of the CustomResourceDefinition (required) * @param body (required) * @param pretty If 'true', then the output is pretty printed. (optional) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call replaceAsync(String namespace, String name, T body, String pretty, final ApiCallback<T> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = replaceValidateBeforeCall(namespace, name, body, pretty, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<T>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; }
/** * (asynchronously) * replace status of the specified CustomResourceDefinition * @param name name of the CustomResourceDefinition (required) * @param body (required) * @param pretty If 'true', then the output is pretty printed. (optional) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call replaceStatusAsync(String namespace, String name, T body, String pretty, final ApiCallback<T> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = replaceStatusValidateBeforeCall(namespace, name, body, pretty, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<T>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; }
public <T> T ifExists(Call c, Class<T> clazz) throws ApiException { try { return (T) apiClient.execute(c, clazz).getData(); } catch (ApiException e) { if ("NotFound".equals(apiExceptionParser.getReason(e))) return null; throw e; } }
Call post(String mode, String username, String password, Callback callback) throws IOException { OkHttpClient client = new OkHttpClient(); RequestBody formBody = new FormEncodingBuilder() .add("mode", mode) .add("username", username + "@snu.in") .add("password", password) .build(); Request request = new Request.Builder() .url("http://192.168.50.1/24online/servlet/E24onlineHTTPClient") .post(formBody) .build(); Call call = client.newCall(request); call.enqueue(callback); return call; }
@Test public void testGetWithoutHeaders() throws Exception { OkHttpClient httpClient = mock(OkHttpClient.class); when(httpClient.newCall(any(Request.class))).thenAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { Call callMock = mock(Call.class); return callMock; } }); NetworkingModule networkingModule = new NetworkingModule(null, "", httpClient); networkingModule.sendRequest( mock(ExecutorToken.class), "GET", "http://somedomain/foo", 0, JavaOnlyArray.of(), null, true, 0); ArgumentCaptor<Request> argumentCaptor = ArgumentCaptor.forClass(Request.class); verify(httpClient).newCall(argumentCaptor.capture()); assertThat(argumentCaptor.getValue().urlString()).isEqualTo("http://somedomain/foo"); // We set the User-Agent header by default assertThat(argumentCaptor.getValue().headers().size()).isEqualTo(1); assertThat(argumentCaptor.getValue().method()).isEqualTo("GET"); }
@Test public void testSuccessfulPostRequest() throws Exception { OkHttpClient httpClient = mock(OkHttpClient.class); when(httpClient.newCall(any(Request.class))).thenAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { Call callMock = mock(Call.class); return callMock; } }); NetworkingModule networkingModule = new NetworkingModule(null, "", httpClient); JavaOnlyMap body = new JavaOnlyMap(); body.putString("string", "This is request body"); networkingModule.sendRequest( mock(ExecutorToken.class), "POST", "http://somedomain/bar", 0, JavaOnlyArray.of(JavaOnlyArray.of("Content-Type", "text/plain")), body, true, 0); ArgumentCaptor<Request> argumentCaptor = ArgumentCaptor.forClass(Request.class); verify(httpClient).newCall(argumentCaptor.capture()); assertThat(argumentCaptor.getValue().urlString()).isEqualTo("http://somedomain/bar"); assertThat(argumentCaptor.getValue().headers().size()).isEqualTo(2); assertThat(argumentCaptor.getValue().method()).isEqualTo("POST"); assertThat(argumentCaptor.getValue().body().contentType().type()).isEqualTo("text"); assertThat(argumentCaptor.getValue().body().contentType().subtype()).isEqualTo("plain"); Buffer contentBuffer = new Buffer(); argumentCaptor.getValue().body().writeTo(contentBuffer); assertThat(contentBuffer.readUtf8()).isEqualTo("This is request body"); }
@Test public void testHeaders() throws Exception { OkHttpClient httpClient = mock(OkHttpClient.class); when(httpClient.newCall(any(Request.class))).thenAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { Call callMock = mock(Call.class); return callMock; } }); NetworkingModule networkingModule = new NetworkingModule(null, "", httpClient); List<JavaOnlyArray> headers = Arrays.asList( JavaOnlyArray.of("Accept", "text/plain"), JavaOnlyArray.of("User-Agent", "React test agent/1.0")); networkingModule.sendRequest( mock(ExecutorToken.class), "GET", "http://someurl/baz", 0, JavaOnlyArray.from(headers), null, true, 0); ArgumentCaptor<Request> argumentCaptor = ArgumentCaptor.forClass(Request.class); verify(httpClient).newCall(argumentCaptor.capture()); Headers requestHeaders = argumentCaptor.getValue().headers(); assertThat(requestHeaders.size()).isEqualTo(2); assertThat(requestHeaders.get("Accept")).isEqualTo("text/plain"); assertThat(requestHeaders.get("User-Agent")).isEqualTo("React test agent/1.0"); }
@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); }
/** * 同步的Get请求 * * @param url url * @return Response */ private Response _getAsyn(String url) throws IOException { final Request request = new Request.Builder() .url(url) .build(); Call call = mOkHttpClient.newCall(request); return call.execute(); }
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); } }); }