@Override public void fetch(final OkHttpNetworkFetchState fetchState, final Callback callback) { fetchState.submitTime = SystemClock.uptimeMillis(); final Uri uri = fetchState.getUri(); try { Request request = new Request.Builder() .cacheControl(new CacheControl.Builder().noStore().build()) .url(uri.toString()) .get() .build(); fetchWithRequest(fetchState, callback, request); } catch (Exception e) { // handle error while creating the request callback.onFailure(e); } }
@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")); }
@Test public void shouldSendGetRequestAndReceiveException() { 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.onFailure(request, new IOException()); return Void.TYPE; }).when(call).enqueue(isA(Callback.class)); final CompletionStage<com.spotify.apollo.Response<ByteString>> response = client.send(com.spotify.apollo.Request.forUri(URI, "GET").withTtl(Duration.ofMillis(100))); verify(okHttpClient).setReadTimeout(100, TimeUnit.MILLISECONDS); assertTrue(response.toCompletableFuture().isCompletedExceptionally()); }
@Override protected Void doInBackground(Void... params) { try { Request.Builder requestBuilder = new Request.Builder() .url(serverAddr + urlPart); switch (method) { case PUT: requestBuilder.put(RequestBody.create(MEDIA_TYPE_JSON, json)); break; case POST: requestBuilder.post(RequestBody.create(MEDIA_TYPE_JSON, json)); break; case DELETE: requestBuilder.delete(RequestBody.create(MEDIA_TYPE_JSON, json)); break; default: break; } Request request = requestBuilder.build(); httpClient.newCall(request).enqueue(new HttpCallback(callback)); } catch (Exception e) { Log.e(TAG, "IOException", e); } return null; }
/** * Run some HTTP queries against a Docker container from image promagent/wildfly-kitchensink-promagent. * <p/> * The Docker container is started by the maven-docker-plugin when running <tt>mvn verify -Pwildfly</tt>. */ @Test public void testWildfly() throws Exception { OkHttpClient client = new OkHttpClient(); Request restRequest = new Request.Builder().url(System.getProperty("deployment.url") + "/rest/members").build(); // Execute REST call Response restResponse = client.newCall(restRequest).execute(); Assertions.assertEquals(restResponse.code(), 200); Assertions.assertTrue(restResponse.body().string().contains("John Smith")); Thread.sleep(100); // metric is incremented after servlet has written the response, wait a little to get the updated metric assertMetrics(client, "1.0"); // Execute REST call again restResponse = client.newCall(restRequest).execute(); Assertions.assertEquals(restResponse.code(), 200); Assertions.assertTrue(restResponse.body().string().contains("John Smith")); Thread.sleep(100); // metric is incremented after servlet has written the response, wait a little to get the updated metric assertMetrics(client, "2.0"); }
private Request createOpenCellIdApiCall() { StringBuilder sb = new StringBuilder(); sb.append("http://www.opencellid.org/cell/get?key=").append(CellTracker.OCID_API_KEY); if (mAimsicdService.getCell().getMCC() != Integer.MAX_VALUE) { sb.append("&mcc=").append(mAimsicdService.getCell().getMCC()); } if (mAimsicdService.getCell().getMNC() != Integer.MAX_VALUE) { sb.append("&mnc=").append(mAimsicdService.getCell().getMNC()); } if (mAimsicdService.getCell().getLAC() != Integer.MAX_VALUE) { sb.append("&lac=").append(mAimsicdService.getCell().getLAC()); } if (mAimsicdService.getCell().getCID() != Integer.MAX_VALUE) { sb.append("&cellid=").append(mAimsicdService.getCell().getCID()); } sb.append("&format=json"); return new Request.Builder() .url(sb.toString()) .get() .build(); }
public void connect(String url) { try { mHttpClient= (OkHttpClient) Class.forName("com.squareup.okhttp.OkHttpClient").newInstance(); } catch (Exception e) { isSupportWebSocket =false; return; } mHttpClient.setConnectTimeout(10, TimeUnit.SECONDS); mHttpClient.setWriteTimeout(10, TimeUnit.SECONDS); // Disable timeouts for read mHttpClient.setReadTimeout(0, TimeUnit.MINUTES); Request request = new Request.Builder().url(url).build(); WebSocketCall call = WebSocketCall.create(mHttpClient, request); call.enqueue(this); }
@Override public void onOpen(WebSocket webSocket, Request arg1, Response arg2) throws IOException { mWebSocket = webSocket; setEnvironment(WXEnvironment.getConfig()); WXSDKManager.getInstance().postOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(WXEnvironment.sApplication, "Has switched to DEBUG mode, you can see the DEBUG information on the browser!", Toast.LENGTH_SHORT).show(); } },0); for (JSDebuggerCallback callback : mCallbacks.values()) { callback.onSuccess(arg2); } WXLogUtils.e("into--[onOpen]"); }
@Around("call(* com.squareup.okhttp.OkHttpClient+.newCall(..))") public Object onOkHttpNew(ProceedingJoinPoint joinPoint) throws Throwable { if (!Configuration.httpMonitorEnable || joinPoint.getArgs().length != 1) { return joinPoint.proceed(); } Object[] args = joinPoint.getArgs(); Request request = (Request) args[0]; //url URL url = request.url(); if (GlobalConfig.isExcludeHost(url.getHost())) { return joinPoint.proceed(); } RespBean bean = new RespBean(); bean.setUrl(url.toString()); bean.setStartTimestamp(System.currentTimeMillis()); startTimeStamp.add(bean); return joinPoint.proceed(); }
public Request authenticateProxy(Proxy proxy, Response response) throws IOException { List<Challenge> challenges = response.challenges(); Request request = response.request(); HttpUrl url = request.httpUrl(); int size = challenges.size(); for (int i = 0; i < size; i++) { Challenge challenge = (Challenge) challenges.get(i); if ("Basic".equalsIgnoreCase(challenge.getScheme())) { InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address(); PasswordAuthentication auth = java.net.Authenticator .requestPasswordAuthentication(proxyAddress.getHostName(), getConnectToInetAddress(proxy, url), proxyAddress.getPort(), url .scheme(), challenge.getRealm(), challenge.getScheme(), url.url(), RequestorType.PROXY); if (auth != null) { return request.newBuilder().header("Proxy-Authorization", Credentials.basic (auth.getUserName(), new String(auth.getPassword()))).build(); } } } return null; }
public static long get(String collection, String user) { try { collection = "lists." + Long.parseLong(collection); } catch (NumberFormatException ignored) { } Request request = new Request.Builder() .url(TWEETMARKER_API_URL + "?api_key=" + API_KEY + "&username=" + user + "&collection" + collection) .get() .build(); try { final Response response = createHttpClientWithoutSSL().newCall(request).execute(); JSONObject json = new JSONObject(response.body().string()); return json.getJSONObject(collection).getLong("id"); } catch (IOException | JSONException | NoSuchAlgorithmException | KeyManagementException e) { Timber.i(e, ""); } return -1; }
public void writeRequestHeaders(Request request) throws IOException { if (this.stream == null) { List<Header> requestHeaders; this.httpEngine.writingRequestHeaders(); boolean permitsRequestBody = this.httpEngine.permitsRequestBody(request); if (this.framedConnection.getProtocol() == Protocol.HTTP_2) { requestHeaders = http2HeadersList(request); } else { requestHeaders = spdy3HeadersList(request); } this.stream = this.framedConnection.newStream(requestHeaders, permitsRequestBody, true); this.stream.readTimeout().timeout((long) this.httpEngine.client.getReadTimeout(), TimeUnit.MILLISECONDS); this.stream.writeTimeout().timeout((long) this.httpEngine.client.getWriteTimeout(), TimeUnit.MILLISECONDS); } }
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; }
private Request networkRequest(Request request) throws IOException { Request.Builder result = request.newBuilder(); if (request.header("Host") == null) { result.header("Host", Util.hostHeader(request.httpUrl())); } if (request.header("Connection") == null) { result.header("Connection", "Keep-Alive"); } if (request.header(AsyncHttpClient.HEADER_ACCEPT_ENCODING) == null) { this.transparentGzip = true; result.header(AsyncHttpClient.HEADER_ACCEPT_ENCODING, AsyncHttpClient.ENCODING_GZIP); } CookieHandler cookieHandler = this.client.getCookieHandler(); if (cookieHandler != null) { OkHeaders.addCookies(result, cookieHandler.get(request.uri(), OkHeaders.toMultimap (result.build().headers(), null))); } if (request.header(Network.USER_AGENT) == null) { result.header(Network.USER_AGENT, Version.userAgent()); } return result.build(); }
/** * 同步的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; }
/** * 异步的get请求 * * @param url * @param callback */ private void _getAsyn(String url, final ResultCallback callback) { final Request request = new Request.Builder() .url(url) .build(); deliveryResult(callback, request); }
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; }
private Request buildMultipartFormRequest(String url, File[] files, String[] fileKeys, Param[] params) { params = validateParam(params); MultipartBuilder builder = new MultipartBuilder() .type(MultipartBuilder.FORM); for (Param param : params) { builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + param.key + "\""), RequestBody.create(null, param.value)); } if (files != null) { RequestBody fileBody = null; for (int i = 0; i < files.length; i++) { File file = files[i]; String fileName = file.getName(); fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileName)), file); //TODO 根据文件名设置contentType builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + fileKeys[i] + "\"; filename=\"" + fileName + "\""), fileBody); } } RequestBody requestBody = builder.build(); return new Request.Builder() .url(url) .post(requestBody) .build(); }
private void sendFailedStringCallback(final Request request, final Exception e, final ResultCallback callback) { mDelivery.post(new Runnable() { @Override public void run() { if (callback != null) callback.onError(request, e); } }); }
private Request buildPostRequest(String url, Param[] params) { if (params == null) { params = new Param[0]; } FormEncodingBuilder builder = new FormEncodingBuilder(); for (Param param : params) { builder.add(param.key, param.value); } RequestBody requestBody = builder.build(); return new Request.Builder() .url(url) .post(requestBody) .build(); }
/** * @param client * @param request * @return * @throws Exception */ private String getResponseJson(OkHttpClient client, Request request) throws Exception { if (client == null || request == null) { Log.e(TAG, "getResponseJson client == null || request == null >> return null;"); return null; } Response response = client.newCall(request).execute(); return response.isSuccessful() ? response.body().string() : null; }
static String get(Request request, Type proxyType) { StringBuilder result = new StringBuilder(); result.append(request.method()); result.append(' '); if (includeAuthorityInRequestLine(request, proxyType)) { result.append(request.httpUrl()); } else { result.append(requestPath(request.httpUrl())); } result.append(" HTTP/1.1"); return result.toString(); }
@Override public void onFailure(Request request, Exception e) { dismissDialog(); Toast.makeText(builder.mContext, "请求出错:" + e.getMessage(), Toast.LENGTH_LONG).show(); if (STATE_REFREH == state) { builder.mRefreshLayout.finishRefresh(); } else if (STATE_MORE == state) { builder.mRefreshLayout.finishRefreshLoadMore(); } }
private void callbackFailure(final BaseCallback callback, final Request request, final IOException e) { mHandler.post(new Runnable() { @Override public void run() { callback.onFailure(request, e); } }); }
@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 void connectToApi() { OkHttpClient okHttpClient = this.createClient(); final Request request = new Request.Builder() .url(this.url) .addHeader(CONTENT_TYPE_LABEL, CONTENT_TYPE_VALUE_JSON) .get() .build(); try { this.response = okHttpClient.newCall(request).execute().body().string(); } catch (IOException e) { e.printStackTrace(); } }
public static Listener stream(String path, String method, List<Pair> queryParams, ApiClient client, io.kubernetes.client.util.WebSockets.SocketListener listener) throws ApiException, IOException { HashMap<String, String> headers = new HashMap<String, String>(); String allProtocols = String.format("%s,%s,%s,%s", V4_STREAM_PROTOCOL, V3_STREAM_PROTOCOL, V2_STREAM_PROTOCOL, V1_STREAM_PROTOCOL); headers.put(STREAM_PROTOCOL_HEADER, allProtocols); headers.put(HttpHeaders.CONNECTION, HttpHeaders.UPGRADE); headers.put(HttpHeaders.UPGRADE, SPDY_3_1); String[] localVarAuthNames = new String[] { "BearerToken" }; Request request = client.buildRequest(path, method, queryParams, new ArrayList<Pair>(), null, headers, new HashMap<String, Object>(), localVarAuthNames, null); return streamRequest(request, client, listener); }
@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")); }
public String execute2String(Request request) { String result = null; try { Response response = okHttpClient.newCall(request).execute(); if (response != null && response.isSuccessful()) { result = response.body().string(); } } catch (IOException e) { e.printStackTrace(); } return result; }
/** * 创建一个工作在IO线程的被观察者(被订阅者)对象 * * @param url */ public <T> Observable<T> createObservable(final String url, final Class<T> clazz) { return Observable.create(new Observable.OnSubscribe<T>() { @Override public void call(Subscriber<? super T> subscriber) { Request.Builder request = new Request.Builder(); Request.Builder builder = request.url(url); String json = execute2String(builder.build()); setData(subscriber, json, clazz); } }).subscribeOn(Schedulers.io()); }
@Override public void onFailure(final Request request, final IOException e) { handler.post(new Runnable() { @Override public void run() { delegate.onFailure(request, e); } }); }
/** * * @param params * @return */ @Override protected String doInBackground(Void... params) { OkHttpClient client = new OkHttpClient(); String cred = Credentials.basic(_key, _secret); FormEncodingBuilder formBody = new FormEncodingBuilder(); formBody.add("grant_type", "client_credentials"); Request request = new Request.Builder() .url(TWITTER_AUTH_URL) .post(formBody.build()) .addHeader("Authorization", cred) .addHeader("ContentType", "application/x-www-form-urlencoded;charset=UTF-8") .addHeader("Accept-Encoding", "gzip") .build(); try { Response response = client.newCall(request).execute(); if (isZipped(response)) { return unzip(response.body()); } else { return response.body().string(); } } catch (IOException e) { e.printStackTrace(); } return null; }
@Before public void setup() { client = new OkHttpClient(); request = new Request.Builder() .url("http://www.vogella.com/index.html") .build(); }
/** * * @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 onRefresh() { if (CellTracker.OCID_API_KEY != null && !CellTracker.OCID_API_KEY.equals("NA")) { Request request = createOpenCellIdApiCall(); okHttpClient.newCall(request).enqueue(getOpenCellIdResponseCallback()); } else { Handler refresh = new Handler(Looper.getMainLooper()); refresh.post(new Runnable() { public void run() { Helpers.sendMsg(getActivity(), getString(R.string.no_opencellid_key_detected)); swipeRefreshLayout.setRefreshing(false); } }); } }
public boolean connect(String url) { OkHttpClient httpClient = new OkHttpClient(); Request request = new Request.Builder().url(url).addHeader("sec-websocket-protocol", "echo-protocol").build(); WebSocketCall.create(httpClient, request).enqueue(new WXWebSocketListener(url)); return true; }