Search in sources :

Example 86 with Callback

use of retrofit2.Callback in project EssayJoke by qiyei2015.

the class OkHttpEngine method post.

@Override
public void post(HttpRequest httpRequest, final IHttpCallback callback) {
    RequestBody requestBody = buildPostRequest(httpRequest);
    Request request = new Request.Builder().url(httpRequest.getUrl()).post(requestBody).build();
    LogManager.e("Post请求路径:", httpRequest.getUrl());
    mClient.newCall(request).enqueue(new Callback() {

        @Override
        public void onFailure(Call call, IOException e) {
            callback.onFail(e);
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (response != null && response.isSuccessful()) {
                callback.onSuccess(response.body().string());
            } else {
                callback.onFail(new Exception("error"));
            }
        }
    });
}
Also used : Response(okhttp3.Response) Call(okhttp3.Call) Callback(okhttp3.Callback) IHttpCallback(com.qiyei.sdk.http.base.IHttpCallback) Request(okhttp3.Request) HttpRequest(com.qiyei.sdk.http.base.HttpRequest) IOException(java.io.IOException) IOException(java.io.IOException) RequestBody(okhttp3.RequestBody)

Example 87 with Callback

use of retrofit2.Callback in project EssayJoke by qiyei2015.

the class RetrofitEngine method test.

// private void ttt(){
// try {
// Field callFactoryField = retrofit.getClass().getDeclaredField("callFactory");
// if (callFactoryField == null){
// LogManager.i(HTTP.TAG,"callFactoryField is null");
// return;
// }
// callFactoryField.setAccessible(true);
// //找到Client
// OkHttpClient client = (OkHttpClient) callFactoryField.get(retrofit);
// if (client == null){
// LogManager.i(HTTP.TAG,"OkHttpClient is null");
// return;
// }
// Field interceptorsField = client.getClass().getDeclaredField("interceptors");
// if (interceptorsField == null){
// LogManager.i(HTTP.TAG,"interceptorsField is null");
// return;
// }
// interceptorsField.setAccessible(true);
// //找到Interceptor
// List<Interceptor> interceptorList = (List<Interceptor>) interceptorsField.get(client);
// 
// if (interceptorList == null || interceptorList.size() <= 0){
// LogManager.i(HTTP.TAG,"interceptorList is null or size is 0");
// return;
// }
// //找到Interceptor
// MyInterceptor interceptor = (MyInterceptor) interceptorList.get(0);
// if (interceptor == null){
// LogManager.i(HTTP.TAG,"MyInterceptor is null ");
// return;
// }
// interceptor.setProgressResponseBody(new ProgressResponseBody(callback));
// //interceptorList.add(0,interceptor);
// 
// //设置回去
// interceptorsField.set(client,interceptorList);
// callFactoryField.set(retrofit,client);
// 
// } catch (NoSuchFieldException e) {
// e.printStackTrace();
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// }
// }
/**
 * 先自行
 */
// private void test2(){
// test(IRetrofitService.class,"getDiscoverList","discovery/v3/",Map.class);
// 
// //获取task要执行的方法的参数
// Map<String,String> params = HttpUtil.gsonToGetParams(task.getRequest());
// 
// Retrofit retrofit = RetrofitFactory.createRetrofit(task.getRequest().getBaseUrl());
// 
// //构造Call
// IRetrofitService service = retrofit.create(IRetrofitService.class);
// Call<Object> call = service.getDiscoverList(params);
// 
// if (call == null){
// return ;
// }
// //设置task到okHttp拦截器中
// setOkHttpInterceptorTag(call,task);
// //将任务加到队列里面
// HttpCallManager.getInstance().addCall(task.getTaskId(),call);
// 
// call.enqueue(new Callback<Object>() {
// 
// @Override
// public void onResponse(Call<Object> call, Response<Object> response) {
// //移除task
// HttpCallManager.getInstance().removeCall(task.getTaskId());
// 
// HttpResponse<R> obj = new HttpResponse<>((R)response.body());
// callback.onSuccess(obj);
// }
// 
// @Override
// public void onFailure(Call<Object> call, Throwable t) {
// //移除task
// HttpCallManager.getInstance().removeCall(task.getTaskId());
// 
// callback.onFailure((Exception) t);
// }
// });
// }
private void test(Class<?> clazz, String methodName, String annotationValue, Class<?>... parameterTypes) {
    try {
        Method method = clazz.getDeclaredMethod(methodName, parameterTypes);
        if (method == null) {
            return;
        }
        method.setAccessible(true);
        GET getAnnotation = method.getAnnotation(GET.class);
        if (getAnnotation == null) {
            return;
        }
        // 获取这个代理的InvocationHandler,这里的Handler是AnnotationFactory libcore.reflect.AnnotationFactory
        InvocationHandler handler = Proxy.getInvocationHandler(getAnnotation);
        if (handler == null) {
            return;
        }
        for (Field field : handler.getClass().getDeclaredFields()) {
            LogManager.i(HTTP.TAG, "field:" + field.getName() + "  type:" + field.getType().getName());
        }
        Field field = handler.getClass().getDeclaredField("elements");
        if (field == null) {
            return;
        }
        field.setAccessible(true);
        // 是AnnotationMember[] 数组
        Object objects = field.get(handler);
        Class<?> type = objects.getClass();
        if (type.isArray()) {
            LogManager.i(HTTP.TAG, "length:" + Array.getLength(objects));
            Object object = Array.get(objects, 0);
            if (object == null) {
                return;
            }
            Class<?> annotationMemberClazz = object.getClass();
            Field valueField = annotationMemberClazz.getDeclaredField("value");
            if (valueField == null) {
                return;
            }
            valueField.setAccessible(true);
            valueField.set(object, annotationValue);
            // 数组设置回去
            Array.set(objects, 0, object);
            LogManager.i(HTTP.TAG, "annotationValue:" + annotationValue);
            field.set(handler, objects);
        }
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}
Also used : Field(java.lang.reflect.Field) GET(retrofit2.http.GET) Method(java.lang.reflect.Method) InvocationHandler(java.lang.reflect.InvocationHandler)

Example 88 with Callback

use of retrofit2.Callback in project EssayJoke by qiyei2015.

the class RetrofitEngine method enqueueGetCall.

@Override
public <T, R> void enqueueGetCall(final HttpTask<T> task, final IHttpCallback<R> callback) {
    Object params = HttpUtil.gsonToGetParams(task.getRequest());
    // 构造Call
    Call call = buildCall(task, params);
    if (call == null) {
        return;
    }
    // 设置task到okHttp拦截器中
    setOkHttpInterceptorTag(call, task);
    // 将任务加到队列里面
    HttpCallManager.getInstance().addCall(task.getTaskId(), call);
    // 发起请求
    call.enqueue(new Callback<R>() {

        @Override
        public void onResponse(Call<R> call, Response<R> response) {
            // 移除task
            HttpCallManager.getInstance().removeCall(task.getTaskId());
            HttpResponse<R> obj = new HttpResponse<>(response.body());
            callback.onSuccess(obj);
        }

        @Override
        public void onFailure(Call<R> call, Throwable t) {
            // 移除task
            HttpCallManager.getInstance().removeCall(task.getTaskId());
            callback.onFailure((Exception) t);
        }
    });
}
Also used : Call(retrofit2.Call) HttpResponse(com.qiyei.sdk.https.server.HttpResponse) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 89 with Callback

use of retrofit2.Callback in project butter-android by butterproject.

the class ButterUpdateManager method downloadFile.

private void downloadFile(final String location) {
    Request request = new Request.Builder().url(location).build();
    mHttpClient.newCall(request).enqueue(new Callback() {

        @Override
        public void onFailure(Call call, IOException e) {
        // uhoh
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (response.isSuccessful()) {
                String fileName = location.substring(location.lastIndexOf('/') + 1);
                File downloadedFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName);
                BufferedSink sink = Okio.buffer(Okio.sink(downloadedFile));
                sink.writeAll(response.body().source());
                sink.close();
                String updateFilePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + "/" + fileName;
                prefManager.getPrefs().edit().putString(SHA1_KEY, hashSHA1(updateFilePath)).putString(UPDATE_FILE, updateFilePath).putLong(SHA1_TIME, System.currentTimeMillis()).apply();
                if (mListener != null) {
                    mListener.updateAvailable(updateFilePath);
                }
            }
        }
    });
}
Also used : Response(okhttp3.Response) Call(okhttp3.Call) Callback(okhttp3.Callback) Request(okhttp3.Request) BufferedSink(okio.BufferedSink) IOException(java.io.IOException) File(java.io.File)

Example 90 with Callback

use of retrofit2.Callback in project AnyMemo by helloworld1.

the class DropboxApiHelper method getUserInfo.

public Single<UserInfo> getUserInfo(@NonNull final String token) {
    return Single.create(new SingleOnSubscribe<UserInfo>() {

        @Override
        public void subscribe(@NonNull final SingleEmitter<UserInfo> emitter) throws Exception {
            RequestBody requestBody = RequestBody.create(null, new byte[0]);
            Request request = new Request.Builder().url(USER_INFO_ENDPOINT).addHeader("Authorization", "Bearer " + token).post(requestBody).build();
            okHttpClient.newCall(request).enqueue(new Callback() {

                @Override
                public void onFailure(Call call, IOException e) {
                    emitter.onError(e);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (!response.isSuccessful()) {
                        emitter.onError(new IOException(getResponseErrorString(call.request(), response)));
                        return;
                    }
                    UserInfo userInfo = new UserInfo();
                    try {
                        JSONObject userInfoObject = new JSONObject(response.body().string());
                        userInfo.accountId = userInfoObject.getString("account_id");
                        userInfo.email = userInfoObject.getString("email");
                        JSONObject nameObject = userInfoObject.getJSONObject("name");
                        userInfo.displayName = nameObject.getString("display_name");
                        emitter.onSuccess(userInfo);
                    } catch (JSONException e) {
                        emitter.onError(e);
                    }
                }
            });
        }
    });
}
Also used : Call(okhttp3.Call) Request(okhttp3.Request) JSONException(org.json.JSONException) UserInfo(org.liberty.android.fantastischmemo.downloader.dropbox.entity.UserInfo) IOException(java.io.IOException) JSONException(org.json.JSONException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) Response(okhttp3.Response) Callback(okhttp3.Callback) JSONObject(org.json.JSONObject) RequestBody(okhttp3.RequestBody)

Aggregations

Callback (okhttp3.Callback)173 IOException (java.io.IOException)151 Call (okhttp3.Call)132 Response (okhttp3.Response)132 Request (okhttp3.Request)110 Call (retrofit2.Call)90 Retrofit (retrofit2.Retrofit)85 ResponseBody (okhttp3.ResponseBody)64 Test (org.junit.Test)56 GsonBuilder (com.google.gson.GsonBuilder)52 Gson (com.google.gson.Gson)46 OkHttpClient (okhttp3.OkHttpClient)44 Response (retrofit2.Response)43 Callback (retrofit2.Callback)42 RequestBody (okhttp3.RequestBody)39 List (java.util.List)34 File (java.io.File)29 CountDownLatch (java.util.concurrent.CountDownLatch)26 Context (android.content.Context)24 RetrofitAPI (com.gladysinc.gladys.Utils.RetrofitAPI)21