/** 取消当前的Call */ public static void cancelCurrentCall() { if (mCall != null && !mCall.isCanceled()) { mCall.cancel(); if (mCall.isCanceled()) { setCancel(true); Logger.i(TAG, "cancelCurrentCall:" + isCancel); mCall = null; } } }
@Test public void interceptorDoesAddUserAgent() throws Exception { Request request = new Request.Builder().url("https://test.desk.com").build(); assertFalse(doesHaveUserAgent(request)); OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.interceptors().add(userAgentInterceptor); Call call = builder.build().newCall(request); Response response = call.execute(); assertTrue(doesHaveUserAgent(response.request())); assertEquals(TEST_USER_AGENT, response.request().header(HEADER_USER_AGENT)); }
/** * 将Json转为Bean * * @param tag * @param url * @param headers * @param beanClass * @param getBeanCallBack * @param <T> */ public static <T> void getBean( Object tag, String url, Map<String, String> headers, final Class<T> beanClass, final GetBeanCallBack<T> getBeanCallBack) { Logger.i(TAG, "getBean url:" + url); setCancel(false); if (mClient != null) { Request.Builder requestBuilder = new Request.Builder(); requestBuilder.tag(tag); requestBuilder.url(url); appendHeaders(requestBuilder, headers); Request request = requestBuilder.build(); mCall = mClient.newCall(request); mCalls.add(mCall); mCall.enqueue( new Callback() { @Override public void onFailure(Call call, IOException e) { Logger.e(TAG, "getBean onFailure" + e.getMessage()); EventBus.getDefault().post(new NetWorkBadEvent()); getBeanCallBack.onFailure(call, e); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { getBeanCallBack.onResponse(GsonUtils.fromJson(response.body().string(), beanClass)); } } }); } }
/** * base 的 get请求 * * @param tag * @param url * @param headers * @param getCallBack */ public static void get( Object tag, String url, Map<String, String> headers, final GetCallBack getCallBack) { Logger.i(TAG, "get url :" + url); setCancel(false); if (mClient != null) { Request.Builder requestBuilder = new Request.Builder(); requestBuilder.tag(tag); requestBuilder.url(url); appendHeaders(requestBuilder, headers); Request request = requestBuilder.build(); mCall = mClient.newCall(request); mCalls.add(mCall); mCall.enqueue( new Callback() { @Override public void onFailure(Call call, IOException e) { getCallBack.onFailure(call, e); Logger.e(TAG, "get onFailure:" + e.getMessage()); EventBus.getDefault().post(new NetWorkBadEvent()); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { getCallBack.onResponse(call, response); } else { getCallBack.onError(response.toString()); } } }); } }
/** 取消所有请求 */ public static void cancelAllCall() { if (mCalls != null && mCalls.size() > 0) { int mCallsSize = mCalls.size(); for (int i = 0; i < mCallsSize; i++) { Call call = mCalls.get(0); if (call != null && !call.isCanceled()) { call.cancel(); if (call.isCanceled()) { mCalls.remove(call); if (!mCalls.contains(call)) { call = null; } } } } setCancel(true); } }
/** * post请求 * * @param tag * @param url * @param headers * @param params * @param postCallBack */ public static void post( Object tag, String url, Map<String, String> headers, Map<String, String> params, final PostCallBack postCallBack) { Logger.i(TAG, "post url :" + url); setCancel(false); RequestBody requestBody = null; FormBody.Builder formBodyBuilder = new FormBody.Builder(); if (params == null || params.size() == 0) { requestBody = formBodyBuilder.build(); } else { for (Map.Entry<String, String> me : params.entrySet()) { formBodyBuilder.add(me.getKey(), me.getValue()); } requestBody = formBodyBuilder.build(); } Request.Builder requestBuilder = new Request.Builder(); requestBuilder.tag(tag); requestBuilder.url(url); appendHeaders(requestBuilder, headers); requestBuilder.post(requestBody); Request request = requestBuilder.build(); mCall = mClient.newCall(request); mCalls.add(mCall); mCall.enqueue( new Callback() { @Override public void onFailure(Call call, IOException e) { Logger.e(TAG, "post onFailure :" + e.toString()); postCallBack.onFailure(call, e); EventBus.getDefault().post(new NetWorkBadEvent()); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { Logger.i(TAG, "post onResponse"); postCallBack.onResponse(call, response); } else { Logger.i(TAG, "post onError: " + response.code()); postCallBack.onError(response.code()); } } }); }
/** * 文件上传 * * @param tag * @param url * @param filePath * @param headers * @param params * @param uploadFileCallBack */ public static void uploadFile( Object tag, String url, String filePath, Map<String, String> headers, Map<String, String> params, final UploadFileCallBack uploadFileCallBack) { Logger.i(TAG, "uploadFile url :" + url); setCancel(false); File file = new File(filePath); MultipartBody.Builder multipartBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM); addParams(multipartBuilder, params); addFiles(multipartBuilder, new Pair<String, File>("file", file)); progerssRequestBody = new ProgressRequestBody(multipartBuilder.build(), uploadFileCallBack); Request.Builder builder = new Request.Builder(); appendHeaders(builder, headers); Request request = builder.tag(tag).url(url).post(progerssRequestBody).build(); mCall = mClient.newCall(request); mCalls.add(mCall); mCall.enqueue( new Callback() { @Override public void onFailure(Call call, IOException e) { Logger.e(TAG, "uploadFile onFailure :" + e.toString()); uploadFileCallBack.onFailure(call, e); EventBus.getDefault().post(new NetWorkBadEvent()); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { Logger.i(TAG, "uploadFile onResponse"); uploadFileCallBack.onResponse(call, response); } else { Logger.i(TAG, "uploadFile onError: " + response.code()); uploadFileCallBack.onError(response.code()); } } }); }
public void cancelTag(Object tag) { Dispatcher dispatcher = mClient.dispatcher(); List<Call> calls = dispatcher.queuedCalls(); for (Call call : calls) { if (call.request().tag().equals(tag)) { call.cancel(); } } calls = dispatcher.runningCalls(); for (Call call : calls) { if (call.request().tag().equals(tag)) { call.cancel(); } } }
/** * post提交Json * * @param tag * @param url * @param headers * @param json * @param postCallBack */ public static void postJson( Object tag, String url, Map<String, String> headers, String json, final PostCallBack postCallBack) { Logger.i(TAG, "postJson url :" + url); setCancel(false); RequestBody postBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), json); Request.Builder requestBuilder = new Request.Builder(); requestBuilder.tag(tag); requestBuilder.url(url); appendHeaders(requestBuilder, headers); requestBuilder.post(postBody); Request request = requestBuilder.build(); mCall = mClient.newCall(request); mCalls.add(mCall); mCall.enqueue( new Callback() { @Override public void onFailure(Call call, IOException e) { Logger.e(TAG, "postJson onFailure :" + e.toString()); postCallBack.onFailure(call, e); EventBus.getDefault().post(new NetWorkBadEvent()); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { Logger.i(TAG, "postJson onResponse"); postCallBack.onResponse(call, response); } else { Logger.i(TAG, "postJson onError: " + response.code()); postCallBack.onError(response.code()); } } }); }
/** * 取消相同的tag请求 * * @param tag */ public static void cancelSameTagCall(Object tag) { if (mClient != null) { Dispatcher dispatcher = mClient.dispatcher(); for (Call call : dispatcher.queuedCalls()) { if (tag.equals(call.request().tag())) { call.cancel(); } } for (Call call : dispatcher.runningCalls()) { if (tag.equals(call.request().tag())) { call.cancel(); } } setCancel(true); } else { Logger.e(TAG, "cancelSameTagCall mClient 为 null"); } }
@Override public T call() throws Exception { Request request = null; Response response = null; Exception exception = null; Call call = null; try { MNSLog.logD("[call] - "); if (context.getCancellationHandler().isCancelled()) { throw new InterruptedIOException("This task is cancelled!"); } Request.Builder requestBuilder = new Request.Builder(); // build request url String url = message.buildCanonicalURL(); MNSUtils.signRequest(message); requestBuilder = requestBuilder.url(url); // set request headers for (String key : message.getHeaders().keySet()) { requestBuilder = requestBuilder.addHeader(key, message.getHeaders().get(key)); } String contentType = message.getHeaders().get(MNSHeaders.CONTENT_TYPE); String content = message.getContent(); // set request body if (message.getContent() != null) { MNSUtils.assertTrue(contentType != null, "Content type can't be null when send data!"); requestBuilder = requestBuilder.method( message.getMethod().toString(), new ProgressTouchableRequestBody( message.getContent().getBytes(), contentType, context.getProgressCallback())); } else { switch (message.getMethod()) { case PUT: requestBuilder = requestBuilder.method( message.getMethod().toString(), RequestBody.create(null, new byte[0])); break; case GET: requestBuilder = requestBuilder.get(); break; case HEAD: requestBuilder = requestBuilder.head(); break; case DELETE: requestBuilder = requestBuilder.delete(); break; default: break; } } request = requestBuilder.build(); if (MNSLog.isEnableLog()) { MNSLog.logD("request url: " + request.url()); Map<String, List<String>> headerMap = request.headers().toMultimap(); for (String key : headerMap.keySet()) { MNSLog.logD("requestHeader " + key + ": " + headerMap.get(key).get(0)); } } call = client.newCall(request); context.getCancellationHandler().setCall(call); // send request response = call.execute(); if (MNSLog.isEnableLog()) { MNSLog.logD("response code: " + response.code() + " for url: " + request.url()); Map<String, List<String>> headerMap = response.headers().toMultimap(); for (String key : headerMap.keySet()) { MNSLog.logD("responseHeader " + key + ": " + headerMap.get(key).get(0)); } } } catch (Exception e) { MNSLog.logE("Encounter local execpiton: " + e.toString()); if (MNSLog.isEnableLog()) { e.printStackTrace(); } exception = new ClientException(e.getMessage(), e); } if (exception == null && (response.code() == 203 || response.code() >= 300)) { try { exception = ResponseParsers.parseResponseErrorXML(response); } catch (IOException e) { exception = new ClientException(e.getMessage(), e); } } else if (exception == null) { try { T result = responseParser.parse(response); if (context.getCompletedCallback() != null) { context.getCompletedCallback().onSuccess(context.getRequest(), result); } return result; } catch (IOException e) { exception = new ClientException(e.getMessage(), e); } } // reconstruct exception caused by manually cancelling if ((call != null && call.isCanceled()) || context.getCancellationHandler().isCancelled()) { exception = new ClientException("Task is cancelled!", exception.getCause(), true); } if (exception instanceof ClientException) { if (context.getCompletedCallback() != null) { context .getCompletedCallback() .onFailure(context.getRequest(), (ClientException) exception, null); } } else { if (context.getCompletedCallback() != null) { context .getCompletedCallback() .onFailure(context.getRequest(), null, (ServiceException) exception); } } throw exception; }
public void cancelDownloadBundleFromURL() { if (mDownloadBundleFromURLCall != null) { mDownloadBundleFromURLCall.cancel(); mDownloadBundleFromURLCall = null; } }
public void downloadBundleFromURL( final BundleDownloadCallback callback, final String jsModulePath, final File outputFile) { final String bundleURL = createBundleURL( getDebugServerHost(), jsModulePath, getDevMode(), getHMR(), getJSMinifyMode()); final Request request = new Request.Builder().url(bundleURL).build(); mDownloadBundleFromURLCall = Assertions.assertNotNull(mClient.newCall(request)); mDownloadBundleFromURLCall.enqueue( new Callback() { @Override public void onFailure(Call call, IOException e) { // ignore callback if call was cancelled if (mDownloadBundleFromURLCall == null || mDownloadBundleFromURLCall.isCanceled()) { mDownloadBundleFromURLCall = null; return; } mDownloadBundleFromURLCall = null; StringBuilder sb = new StringBuilder(); sb.append("Could not connect to development server.\n\n") .append("Try the following to fix the issue:\n") .append("\u2022 Ensure that the packager server is running\n") .append( "\u2022 Ensure that your device/emulator is connected to your machine and has USB debugging enabled - run 'adb devices' to see a list of connected devices\n") .append( "\u2022 If you're on a physical device connected to the same machine, run 'adb reverse tcp:8081 tcp:8081' to forward requests from your device\n") .append( "\u2022 If your device is on the same Wi-Fi network, set 'Debug server host & port for device' in 'Dev settings' to your machine's IP address and the port of the local dev server - e.g. 10.0.1.1:8081\n\n") .append("URL: ") .append(call.request().url().toString()); callback.onFailure(new DebugServerException(sb.toString())); } @Override public void onResponse(Call call, Response response) throws IOException { // ignore callback if call was cancelled if (mDownloadBundleFromURLCall == null || mDownloadBundleFromURLCall.isCanceled()) { mDownloadBundleFromURLCall = null; return; } mDownloadBundleFromURLCall = null; // Check for server errors. If the server error has the expected form, fail with more // info. if (!response.isSuccessful()) { String body = response.body().string(); DebugServerException debugServerException = DebugServerException.parse(body); if (debugServerException != null) { callback.onFailure(debugServerException); } else { StringBuilder sb = new StringBuilder(); sb.append("The development server returned response error code: ") .append(response.code()) .append("\n\n") .append("URL: ") .append(call.request().url().toString()) .append("\n\n") .append("Body:\n") .append(body); callback.onFailure(new DebugServerException(sb.toString())); } return; } Sink output = null; try { output = Okio.sink(outputFile); Okio.buffer(response.body().source()).readAll(output); callback.onSuccess(); } finally { if (output != null) { output.close(); } } } }); }
/** * 下载 * * @param tag * @param url * @param targetPath * @param fileName * @param avaiable * @param downLoadCallBack */ public static void downLoad( Object tag, final String url, final String targetPath, final String fileName, final long avaiable, final DownLoadCallBack downLoadCallBack) { Logger.i(TAG, "downLoad url:" + url); setCancel(false); if (TextUtils.isEmpty(url)) throw new NullPointerException("url can't be null"); if (TextUtils.isEmpty(targetPath)) throw new NullPointerException("targetPath can't be null"); if (mClient != null) { Logger.i(TAG, "-----"); final Request request = new Request.Builder().tag(tag).url(url).build(); mCall = mClient.newCall(request); mCalls.add(mCall); Logger.i(TAG, "-----url=" + url + ",targetPath=" + targetPath + ",fileName=" + fileName); mCall.enqueue( new Callback() { @Override public void onFailure(Call call, IOException e) { Logger.e(TAG, "downLoad onFailure:" + e.getMessage()); downLoadCallBack.onFailure(call, e); EventBus.getDefault().post(new NetWorkBadEvent()); } @Override public void onResponse(Call call, Response response) { Logger.i(TAG, "-----response.isSuccessful()=" + response.isSuccessful()); if (response.isSuccessful()) { File targetFile = new File(targetPath); if (!targetFile.exists()) { targetFile.mkdirs(); } Logger.i(TAG, "-----targetFile=" + targetFile); long total = response.body().contentLength(); int current = 0; BufferedInputStream bis = null; BufferedOutputStream bos = null; // 判断内存卡剩余内存的大小 if (avaiable > total) { try { Logger.i(TAG, "downLoad onStart total:" + total); downLoadCallBack.onStart(total); InputStream is = response.body().byteStream(); bis = new BufferedInputStream(is); FileOutputStream fos = new FileOutputStream(targetFile.getAbsolutePath() + "/" + fileName); Logger.i(TAG, "文件存储:" + targetFile.getAbsolutePath() + "/" + fileName); bos = new BufferedOutputStream(fos); byte[] buffer = new byte[1024]; int len = 0; while (!isCancel && ((len = bis.read(buffer)) != -1)) { current += len; Logger.i(TAG, "downLoad onLoading current:" + current); bos.write(buffer, 0, len); downLoadCallBack.onLoading(current, total); } if (current < total) { Logger.i(TAG, "downLoad onCancel"); downLoadCallBack.onCancel(); } } catch (IOException e) { Logger.e(TAG, "读写流出错:" + e.getMessage()); downLoadCallBack.onError(e); } finally { try { if (bos != null) { bos.close(); bos = null; } } catch (IOException e) { e.printStackTrace(); downLoadCallBack.onError(e); } try { if (bis != null) { bis.close(); bis = null; } } catch (IOException e) { e.printStackTrace(); downLoadCallBack.onError(e); } if (current == total) { Logger.i(TAG, "downLoad onSucceed" + "文件保存在" + targetPath + "/" + fileName); downLoadCallBack.onSucceed(); } } } else { Logger.i(TAG, "downLoad onSdCardLackMemory"); downLoadCallBack.onSdCardLackMemory(total, avaiable); } } } }); } }
@Override public void onError(Call call, Exception e, int id) { Log.d("MyStringCallback", "onError: " + call.toString()); }