List of usage examples for com.squareup.okhttp Call execute
public Response execute() throws IOException
From source file:com.hippo.nimingban.client.ac.ACEngine.java
License:Apache License
public static Void doCreatePost(Call call) throws Exception { String body = null;/*from w w w. jav a 2 s . c o m*/ try { Response response = call.execute(); ResponseUtils.storeCookies(response); body = response.body().string(); try { JSONObject jo = JSON.parseObject(body); if (jo.getBoolean("success")) { return null; } else { throw new NMBException(ACSite.getInstance(), jo.getString("msg")); } } catch (Exception e) { if (body.contains("class=\"success\"")) { return null; } else { throw e; } } } catch (Exception e) { throwException(call, body, e); throw e; } }
From source file:com.hippo.nimingban.client.ac.ACEngine.java
License:Apache License
public static List<ACSearchItem> doSearch(Call call) throws Exception { String body = null;/*w ww. j a va2s. co m*/ try { Response response = call.execute(); body = response.body().string(); JSONArray ja = JSON.parseObject(body).getJSONObject("hits").getJSONArray("hits"); List<ACSearchItem> result = new ArrayList<>(); for (int i = 0, n = ja.size(); i < n; i++) { JSONObject jo = ja.getJSONObject(i); ACSearchItem item = jo.getObject("_source", ACSearchItem.class); item.id = jo.getString("_id"); item.generate(ACSite.getInstance()); result.add(item); } return result; } catch (Exception e) { throwException(call, body, e); throw e; } }
From source file:com.hippo.nimingban.client.ConvertEngine.java
License:Apache License
public static String doConvert(Call call) throws Exception { try {/*from w w w. j av a2 s .c o m*/ Response response = call.execute(); int code = response.code(); if (code != 200) { throw new ResponseCodeException(code); } return response.body().string(); } catch (IOException e) { if (call.isCanceled()) { throw new CancelledException(); } else { throw e; } } }
From source file:com.hippo.nimingban.client.UpdateEngine.java
License:Apache License
public static UpdateStatus doUpdate(Call call) throws Exception { try {/*ww w. j av a 2 s .c om*/ Response response = call.execute(); String body = response.body().string(); return JSON.parseObject(body, UpdateStatus.class); } catch (IOException e) { if (call.isCanceled()) { throw new CancelledException(); } else { throw e; } } }
From source file:com.ichg.service.volley.OkHttpStack.java
License:Open Source License
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { OkHttpClient client = mClient.clone(); int timeoutMs = request.getTimeoutMs(); client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS); com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder(); okHttpRequestBuilder.url(request.getUrl()); Map<String, String> headers = request.getHeaders(); for (final String name : headers.keySet()) { okHttpRequestBuilder.addHeader(name, headers.get(name)); }//w ww . ja v a2s .co m for (final String name : additionalHeaders.keySet()) { okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name)); } setConnectionParametersForRequest(okHttpRequestBuilder, request); com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build(); Call okHttpCall = client.newCall(okHttpRequest); Response okHttpResponse = okHttpCall.execute(); StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()), okHttpResponse.code(), okHttpResponse.message()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromOkHttpResponse(okHttpResponse)); Headers responseHeaders = okHttpResponse.headers(); for (int i = 0, len = responseHeaders.size(); i < len; i++) { final String name = responseHeaders.name(i), value = responseHeaders.value(i); if (name != null) { response.addHeader(new BasicHeader(name, value)); } } return response; }
From source file:com.kubeiwu.easyandroid.easyhttp.core.retrofit.KOkHttpCall.java
License:Apache License
public Response<T> execute() throws IOException { synchronized (this) { if (executed) throw new IllegalStateException("Already executed"); executed = true;//from w w w. ja va 2 s .c o m } final Request request = createRequest(); com.squareup.okhttp.Call rawCall = client.newCall(request); if (canceled) { rawCall.cancel(); } this.rawCall = rawCall; // ----------------------------------------------------------------------cgp String cacheMode = getCacheMode(request); if (!TextUtils.isEmpty(cacheMode)) { cacheMode = cacheMode.trim().toLowerCase(Locale.CHINA); switch (cacheMode) { case CacheMode.LOAD_NETWORK_ELSE_CACHE:// ?? Response<T> response; try { response = parseResponse(rawCall.execute(), request); } catch (Exception e) { response = execCacheRequest(request); } return response; case CacheMode.LOAD_CACHE_ELSE_NETWORK:// ? // ---------------------? response = execCacheRequest(request); if (response != null) { return response; } // ---------------------? // case CacheMode.LOAD_DEFAULT: case CacheMode.LOAD_NETWORK_ONLY: default: break;// } } // ----------------------------------------------------------------------cgp return parseResponse(rawCall.execute(), request); }
From source file:com.liferay.mobile.android.auth.CookieSignIn.java
License:Open Source License
public static Session signIn(Session session) throws Exception { CookieSignIn cookieSignIn = new CookieSignIn(session); Call call = cookieSignIn.signIn(); Response response = call.execute(); return parseResponse(response, session.getServer(), cookieSignIn.cookieManager, getCookieAuthentication(session.getAuthentication())); }
From source file:com.liferay.mobile.android.http.client.OkHttpClientImpl.java
License:Open Source License
protected Response send(Builder builder, final Request request) throws Exception { builder = builder.url(request.getURL()); builder.tag(request.getTag());/*from ww w. j a v a2s . c o m*/ OkHttpClient client = getClient(request.getConnectionTimeout()); authenticate(client, request); addHeaders(builder, request); Call call = client.newCall(builder.build()); final Callback callback = request.getCallback(); if (callback == null) { return new Response(call.execute()); } else { sendAsync(call, callback); return null; } }
From source file:com.liulishuo.filedownloader.services.FileDownloadRunnable.java
License:Apache License
@Override public void run() { isPending = false;/*from ww w . jav a 2 s . c o m*/ isRunning = true; int retryingTimes = 0; Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); FileDownloadModel model = this.downloadModel; if (model == null) { FileDownloadLog.e(this, "start runnable but model == null?? %s", getId()); this.downloadModel = helper.find(getId()); if (this.downloadModel == null) { FileDownloadLog.e(this, "start runnable but downloadMode == null?? %s", getId()); return; } model = this.downloadModel; } if (model.getStatus() != FileDownloadStatus.pending) { FileDownloadLog.e(this, "start runnable but status err %s", model.getStatus()); // ??urlpath(????) ?? onError(new RuntimeException(String.format("start runnable but status err %s", model.getStatus()))); return; } // do { long soFar = 0; try { if (model.isCanceled()) { FileDownloadLog.d(this, "already canceled %d %d", model.getId(), model.getStatus()); break; } FileDownloadLog.d(FileDownloadRunnable.class, "start download %s %s", getId(), model.getUrl()); checkIsContinueAvailable(); Request.Builder headerBuilder = new Request.Builder().url(url); addHeader(headerBuilder); headerBuilder.tag(this.getId()); // ?cache?REST? headerBuilder.cacheControl(CacheControl.FORCE_NETWORK); Call call = client.newCall(headerBuilder.get().build()); Response response = call.execute(); final boolean isSucceedStart = response.code() == 200; final boolean isSucceedContinue = response.code() == 206 && isContinueDownloadAvailable; if (isSucceedStart || isSucceedContinue) { long total = downloadTransfer.getTotalBytes(); if (isSucceedStart || total == 0) { total = response.body().contentLength(); } if (isSucceedContinue) { soFar = downloadTransfer.getSoFarBytes(); FileDownloadLog.d(this, "add range %d %d", downloadTransfer.getSoFarBytes(), downloadTransfer.getTotalBytes()); } InputStream inputStream = null; RandomAccessFile accessFile = getRandomAccessFile(isSucceedContinue); try { inputStream = response.body().byteStream(); byte[] buff = new byte[BUFFER_SIZE]; maxNotifyBytes = maxNotifyCounts <= 0 ? -1 : total / maxNotifyCounts; updateHeader(response); onConnected(isSucceedContinue, soFar, total); do { int byteCount = inputStream.read(buff); if (byteCount == -1) { break; } accessFile.write(buff, 0, byteCount); //write buff soFar += byteCount; if (accessFile.length() < soFar) { // ?? throw new RuntimeException( String.format("file be changed by others when downloading %d %d", accessFile.length(), soFar)); } else { onProcess(soFar, total); } if (isCancelled()) { onPause(); return; } } while (true); if (soFar == total) { onComplete(total); // ? break; } else { throw new RuntimeException( String.format("sofar[%d] not equal total[%d]", soFar, total)); } } finally { if (inputStream != null) { inputStream.close(); } if (accessFile != null) { accessFile.close(); } } } else { throw new RuntimeException(String.format("response code error: %d", response.code())); } } catch (Throwable ex) { // TODO ??????? if (autoRetryTimes > retryingTimes++) { // retry onRetry(ex, retryingTimes, soFar); continue; } else { // error onError(ex); break; } } finally { isRunning = false; } } while (true); }
From source file:com.moesif.android.okhttp2.MoesifOkHttp2Stack.java
License:Open Source License
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { OkHttpClient client = mClient.clone(); int timeoutMs = request.getTimeoutMs(); client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.networkInterceptors().add(new MoesifOkHttp2Interceptor()); com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder(); okHttpRequestBuilder.url(request.getUrl()); Map<String, String> headers = request.getHeaders(); for (final String name : headers.keySet()) { okHttpRequestBuilder.addHeader(name, headers.get(name)); }/*from www. j ava2s. c om*/ for (final String name : additionalHeaders.keySet()) { okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name)); } setConnectionParametersForRequest(okHttpRequestBuilder, request); com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build(); Call okHttpCall = client.newCall(okHttpRequest); Response okHttpResponse = okHttpCall.execute(); StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()), okHttpResponse.code(), okHttpResponse.message()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromOkHttpResponse(okHttpResponse)); Headers responseHeaders = okHttpResponse.headers(); for (int i = 0, len = responseHeaders.size(); i < len; i++) { final String name = responseHeaders.name(i), value = responseHeaders.value(i); if (name != null) { response.addHeader(new BasicHeader(name, value)); } } return response; }