Search in sources :

Example 31 with GET

use of retrofit2.http.GET 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 32 with GET

use of retrofit2.http.GET in project reark by reark.

the class FetcherBase method completeRequest.

protected void completeRequest(int requestId, @NonNull String uri, boolean withValue) {
    Log.v(TAG, String.format("completeRequest(%s, %s, %s)", requestId, get(uri), withValue));
    lock(requestId);
    NetworkRequestStatus status = new NetworkRequestStatus.Builder().uri(uri).listeners(getListeners(requestId)).completed(withValue).build();
    try {
        updateNetworkRequestStatus.accept(status);
    } catch (Exception e) {
        Log.e(TAG, "Error updating status", e);
    }
    release(requestId);
}
Also used : NetworkRequestStatus(io.reark.reark.pojo.NetworkRequestStatus) HttpException(retrofit2.HttpException)

Example 33 with GET

use of retrofit2.http.GET in project graylog2-server by Graylog2.

the class RemoteInterfaceProvider method get.

public <T> T get(Node node, final String authorizationToken, Class<T> interfaceClass) {
    final OkHttpClient okHttpClient = this.okHttpClient.newBuilder().addInterceptor(chain -> {
        final Request original = chain.request();
        Request.Builder builder = original.newBuilder().header(HttpHeaders.ACCEPT, MediaType.JSON_UTF_8.toString()).header(CsrfProtectionFilter.HEADER_NAME, "Graylog Server").method(original.method(), original.body());
        if (authorizationToken != null) {
            builder = builder.header(HttpHeaders.AUTHORIZATION, authorizationToken).header(SessionAuthenticator.X_GRAYLOG_NO_SESSION_EXTENSION, "true");
        }
        return chain.proceed(builder.build());
    }).build();
    final Retrofit retrofit = new Retrofit.Builder().baseUrl(node.getTransportAddress()).addConverterFactory(JacksonConverterFactory.create(objectMapper)).client(okHttpClient).build();
    return retrofit.create(interfaceClass);
}
Also used : Inject(javax.inject.Inject) MediaType(com.google.common.net.MediaType) Request(okhttp3.Request) Node(org.graylog2.cluster.Node) OkHttpClient(okhttp3.OkHttpClient) HttpHeaders(com.google.common.net.HttpHeaders) JacksonConverterFactory(retrofit2.converter.jackson.JacksonConverterFactory) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) CsrfProtectionFilter(org.glassfish.jersey.client.filter.CsrfProtectionFilter) Retrofit(retrofit2.Retrofit) SessionAuthenticator(org.graylog2.security.realm.SessionAuthenticator) Retrofit(retrofit2.Retrofit) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request)

Example 34 with GET

use of retrofit2.http.GET in project mobile-sdk-android by meniga.

the class MenigaCategoryConverter method responseBodyConverter.

@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
    Type typeOfMenigaCategoryList = new TypeToken<List<MenigaCategory>>() {
    }.getType();
    Type typeOfMenigaCategory = new TypeToken<MenigaCategory>() {
    }.getType();
    Type typeOfMenigaUserCategoryList = new TypeToken<List<MenigaUserCategory>>() {
    }.getType();
    Type typeOfMenigaUserCategory = new TypeToken<MenigaUserCategory>() {
    }.getType();
    if (typeOfMenigaCategoryList.equals(type) || typeOfMenigaUserCategoryList.equals(type)) {
        return new Converter<ResponseBody, Object>() {

            @Override
            public List<MenigaCategory> convert(ResponseBody resBody) throws IOException {
                Gson gson = GsonProvider.getGson();
                MenigaCategory[] catsRaw = gson.fromJson(getAsArray(resBody.byteStream()), MenigaCategory[].class);
                List<MenigaCategory> cats = new ArrayList<>();
                for (MenigaCategory cat : catsRaw) {
                    if (cat.getIsPublic()) {
                        cats.add(cat);
                    } else {
                        cats.add(new MenigaUserCategory(cat));
                    }
                    for (int i = 0; i < cat.getChildren().size(); i++) {
                        MenigaCategory child = cat.getChildren().get(i);
                        if (!child.getIsPublic()) {
                            cat.getChildren().set(i, new MenigaUserCategory(child));
                        }
                    }
                }
                return cats;
            }
        };
    } else if (typeOfMenigaCategory.equals(type) || typeOfMenigaUserCategory.equals(type)) {
        return new Converter<ResponseBody, Object>() {

            @Override
            public MenigaCategory convert(ResponseBody resBody) throws IOException {
                Gson gson = GsonProvider.getGson();
                MenigaCategory catRaw = gson.fromJson(getAsObject(resBody.byteStream()), MenigaCategory.class);
                if (catRaw.getIsPublic()) {
                    return catRaw;
                } else {
                    return new MenigaUserCategory(catRaw);
                }
            }
        };
    }
    return null;
}
Also used : ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) MenigaCategory(com.meniga.sdk.models.categories.MenigaCategory) IOException(java.io.IOException) MenigaUserCategory(com.meniga.sdk.models.categories.MenigaUserCategory) ResponseBody(okhttp3.ResponseBody) Type(java.lang.reflect.Type) Converter(retrofit2.Converter) ArrayList(java.util.ArrayList) List(java.util.List)

Example 35 with GET

use of retrofit2.http.GET in project plaid by nickbutcher.

the class DribbbleShot method onCreate.

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dribbble_shot);
    dribbblePrefs = DribbblePrefs.get(this);
    circleTransform = new CircleTransform(this);
    ButterKnife.bind(this);
    shotDescription = getLayoutInflater().inflate(R.layout.dribbble_shot_description, commentsList, false);
    shotSpacer = shotDescription.findViewById(R.id.shot_spacer);
    title = shotDescription.findViewById(R.id.shot_title);
    description = shotDescription.findViewById(R.id.shot_description);
    likeCount = (Button) shotDescription.findViewById(R.id.shot_like_count);
    viewCount = (Button) shotDescription.findViewById(R.id.shot_view_count);
    share = (Button) shotDescription.findViewById(R.id.shot_share_action);
    playerName = (TextView) shotDescription.findViewById(R.id.player_name);
    playerAvatar = (ImageView) shotDescription.findViewById(R.id.player_avatar);
    shotTimeAgo = (TextView) shotDescription.findViewById(R.id.shot_time_ago);
    setupCommenting();
    commentsList.addOnScrollListener(scrollListener);
    commentsList.setOnFlingListener(flingListener);
    back.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            setResultAndFinish();
        }
    });
    fab.setOnClickListener(fabClick);
    chromeFader = new ElasticDragDismissFrameLayout.SystemChromeFader(this) {

        @Override
        public void onDragDismissed() {
            setResultAndFinish();
        }
    };
    final Intent intent = getIntent();
    if (intent.hasExtra(EXTRA_SHOT)) {
        shot = intent.getParcelableExtra(EXTRA_SHOT);
        bindShot(true);
    } else if (intent.getData() != null) {
        final HttpUrl url = HttpUrl.parse(intent.getDataString());
        if (url.pathSize() == 2 && url.pathSegments().get(0).equals("shots")) {
            try {
                final String shotPath = url.pathSegments().get(1);
                final long id = Long.parseLong(shotPath.substring(0, shotPath.indexOf("-")));
                final Call<Shot> shotCall = dribbblePrefs.getApi().getShot(id);
                shotCall.enqueue(new Callback<Shot>() {

                    @Override
                    public void onResponse(Call<Shot> call, Response<Shot> response) {
                        shot = response.body();
                        bindShot(false);
                    }

                    @Override
                    public void onFailure(Call<Shot> call, Throwable t) {
                        reportUrlError();
                    }
                });
            } catch (NumberFormatException | StringIndexOutOfBoundsException ex) {
                reportUrlError();
            }
        } else {
            reportUrlError();
        }
    }
}
Also used : Call(retrofit2.Call) CircleTransform(io.plaidapp.util.glide.CircleTransform) CustomTabsIntent(android.support.customtabs.CustomTabsIntent) Intent(android.content.Intent) ImageView(android.widget.ImageView) BindView(butterknife.BindView) View(android.view.View) AuthorTextView(io.plaidapp.ui.widget.AuthorTextView) ForegroundImageView(io.plaidapp.ui.widget.ForegroundImageView) TextView(android.widget.TextView) FabOverlapTextView(io.plaidapp.ui.widget.FabOverlapTextView) ParallaxScrimageView(io.plaidapp.ui.widget.ParallaxScrimageView) RecyclerView(android.support.v7.widget.RecyclerView) HttpUrl(okhttp3.HttpUrl) Response(retrofit2.Response) ElasticDragDismissFrameLayout(io.plaidapp.ui.widget.ElasticDragDismissFrameLayout) Callback(retrofit2.Callback)

Aggregations

ResponseBody (okhttp3.ResponseBody)61 Test (org.junit.Test)54 Request (okhttp3.Request)52 Response (retrofit2.Response)27 Retrofit (retrofit2.Retrofit)23 Query (retrofit2.http.Query)15 List (java.util.List)14 IOException (java.io.IOException)12 OkHttpClient (okhttp3.OkHttpClient)12 HttpUrl (okhttp3.HttpUrl)10 Path (retrofit2.http.Path)10 ArrayList (java.util.ArrayList)9 BrainSentences (com.gladysinc.gladys.Models.BrainSentences)8 RetrofitAPI (com.gladysinc.gladys.Utils.RetrofitAPI)8 SelfSigningClientBuilder (com.gladysinc.gladys.Utils.SelfSigningClientBuilder)8 ServiceResponse (com.microsoft.rest.ServiceResponse)8 Call (retrofit2.Call)8 Url (retrofit2.http.Url)8 Uri (android.net.Uri)6 View (android.view.View)6