Search in sources :

Example 6 with GET

use of retrofit2.http.GET in project retrofit by square.

the class RequestBuilderTest method multipartPartsShouldBeInOrder.

@Test
public void multipartPartsShouldBeInOrder() throws IOException {
    class Example {

        @Multipart
        @POST("/foo")
        Call<ResponseBody> get(@Part("first") String data, @Part("second") String dataTwo, @Part("third") String dataThree) {
            return null;
        }
    }
    Request request = buildRequest(Example.class, "firstParam", "secondParam", "thirdParam");
    MultipartBody body = (MultipartBody) request.body();
    Buffer buffer = new Buffer();
    body.writeTo(buffer);
    String readBody = buffer.readUtf8();
    assertThat(readBody.indexOf("firstParam")).isLessThan(readBody.indexOf("secondParam"));
    assertThat(readBody.indexOf("secondParam")).isLessThan(readBody.indexOf("thirdParam"));
}
Also used : Buffer(okio.Buffer) Part(retrofit2.http.Part) MultipartBody(okhttp3.MultipartBody) Request(okhttp3.Request) ResponseBody(okhttp3.ResponseBody) Test(org.junit.Test)

Example 7 with GET

use of retrofit2.http.GET in project retrofit by square.

the class RequestBuilderTest method getWithUrlAbsoluteSameHost.

@Test
public void getWithUrlAbsoluteSameHost() {
    class Example {

        @GET
        Call<ResponseBody> method(@Url String url) {
            return null;
        }
    }
    Request request = buildRequest(Example.class, "http://example.com/foo/bar/");
    assertThat(request.method()).isEqualTo("GET");
    assertThat(request.headers().size()).isZero();
    assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
    assertThat(request.body()).isNull();
}
Also used : Request(okhttp3.Request) Url(retrofit2.http.Url) HttpUrl(okhttp3.HttpUrl) ResponseBody(okhttp3.ResponseBody) Test(org.junit.Test)

Example 8 with GET

use of retrofit2.http.GET in project retrofit by square.

the class RequestBuilderTest method getWithHeaderMap.

@Test
public void getWithHeaderMap() {
    class Example {

        @GET("/search")
        Call<ResponseBody> method(@HeaderMap Map<String, Object> headers) {
            return null;
        }
    }
    Map<String, Object> headers = new LinkedHashMap<>();
    headers.put("Accept", "text/plain");
    headers.put("Accept-Charset", "utf-8");
    Request request = buildRequest(Example.class, headers);
    assertThat(request.method()).isEqualTo("GET");
    assertThat(request.url().toString()).isEqualTo("http://example.com/search");
    assertThat(request.body()).isNull();
    assertThat(request.headers().size()).isEqualTo(2);
    assertThat(request.header("Accept")).isEqualTo("text/plain");
    assertThat(request.header("Accept-Charset")).isEqualTo("utf-8");
}
Also used : HeaderMap(retrofit2.http.HeaderMap) Request(okhttp3.Request) PartMap(retrofit2.http.PartMap) HashMap(java.util.HashMap) HeaderMap(retrofit2.http.HeaderMap) FieldMap(retrofit2.http.FieldMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) QueryMap(retrofit2.http.QueryMap) ResponseBody(okhttp3.ResponseBody) LinkedHashMap(java.util.LinkedHashMap) Test(org.junit.Test)

Example 9 with GET

use of retrofit2.http.GET in project retrofit by square.

the class RetrofitTest method callCallCustomAdapter.

@Test
public void callCallCustomAdapter() {
    final AtomicBoolean factoryCalled = new AtomicBoolean();
    final AtomicBoolean adapterCalled = new AtomicBoolean();
    class MyCallAdapterFactory extends CallAdapter.Factory {

        @Override
        public CallAdapter<?, ?> get(final Type returnType, Annotation[] annotations, Retrofit retrofit) {
            factoryCalled.set(true);
            if (getRawType(returnType) != Call.class) {
                return null;
            }
            return new CallAdapter<Object, Call<?>>() {

                @Override
                public Type responseType() {
                    return getParameterUpperBound(0, (ParameterizedType) returnType);
                }

                @Override
                public Call<Object> adapt(Call<Object> call) {
                    adapterCalled.set(true);
                    return call;
                }
            };
        }
    }
    Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).addCallAdapterFactory(new MyCallAdapterFactory()).build();
    CallMethod example = retrofit.create(CallMethod.class);
    assertThat(example.getResponseBody()).isNotNull();
    assertThat(factoryCalled.get()).isTrue();
    assertThat(adapterCalled.get()).isTrue();
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MediaType(okhttp3.MediaType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) ToStringConverterFactory(retrofit2.helpers.ToStringConverterFactory) NonMatchingCallAdapterFactory(retrofit2.helpers.NonMatchingCallAdapterFactory) DelegatingCallAdapterFactory(retrofit2.helpers.DelegatingCallAdapterFactory) NonMatchingConverterFactory(retrofit2.helpers.NonMatchingConverterFactory) Test(org.junit.Test)

Example 10 with GET

use of retrofit2.http.GET in project GitTest by xiaoxige.

the class MainActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    testView = (TestView) findViewById(R.id.testView);
    testView.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            MainActivityPermissionsDispatcher.showCameraWithPermissionCheck(MainActivity.this);
        }
    });
    try {
        ApplicationInfo appInfo = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
        String appMV = appInfo.metaData.getString("MTA_CHANNEL");
        Toast.makeText(MainActivity.this, "appMV = " + appMV, Toast.LENGTH_SHORT).show();
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    simpleDraweeView = (SimpleDraweeView) findViewById(R.id.simpleDraweeView);
    testView.setProgress(100, false);
    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            testView.setProgress(3, true);
        }
    }, 2000);
    GenericDraweeHierarchy hierarchy = simpleDraweeView.getHierarchy();
    RoundingParams roundingParams = new RoundingParams();
    roundingParams.setBorder(Color.RED, 10);
    roundingParams.setRoundAsCircle(true);
    hierarchy.setRoundingParams(roundingParams);
    simpleDraweeView.setHierarchy(hierarchy);
    ControllerListener listener = new BaseControllerListener() {

        @Override
        public void onFinalImageSet(String id, @Nullable Object imageInfo, @Nullable Animatable animatable) {
            super.onFinalImageSet(id, imageInfo, animatable);
        }
    };
    DraweeController controller = Fresco.newDraweeControllerBuilder().setUri(new Uri.Builder().scheme(UriUtil.LOCAL_RESOURCE_SCHEME).path(String.valueOf(R.mipmap.ic_launcher)).build()).setOldController(simpleDraweeView.getController()).setControllerListener(listener).build();
    simpleDraweeView.setController(controller);
    /**
     * 网络相关(retrofit+rxjava+rxlife+stetho)
     */
    OkHttpClient client = new OkHttpClient.Builder().connectTimeout(5000, TimeUnit.SECONDS).readTimeout(5000, TimeUnit.SECONDS).writeTimeout(5000, TimeUnit.SECONDS).addNetworkInterceptor(new Interceptor() {

        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Headers headers = request.headers();
            Headers build = headers.newBuilder().add("version", "1.0").add("token", "xiaoxige").build();
            request = request.newBuilder().headers(build).build();
            Log.e("TAG", "url = " + request.url().uri().toString());
            String method = request.method();
            if (method.equals("GET") || method.equals("DELETE")) {
                HttpUrl url = request.url();
                HttpUrl httpUrl = url.newBuilder().addQueryParameter("xiaoxige", "one").addQueryParameter("zhuxiaoan", "two").build();
                request = request.newBuilder().url(httpUrl).build();
            } else {
                RequestBody body = request.body();
                if (body != null) {
                    Buffer buffer = new Buffer();
                    body.writeTo(buffer);
                    String readUtf8 = buffer.readUtf8();
                    // 可能需要对body进行加密
                    // TODO: 2017/11/3
                    RequestBody requestBody = RequestBody.create(body.contentType(), readUtf8);
                    request = request.newBuilder().method(method, requestBody).build();
                }
            }
            return chain.proceed(request);
        }
    }).addNetworkInterceptor(new StethoInterceptor()).build();
    Retrofit retrofit = new Retrofit.Builder().baseUrl("http://www.baidu.com").addConverterFactory(ScalarsConverterFactory.create()).addConverterFactory(GsonConverterFactory.create()).client(client).build();
    final NetApi api = retrofit.create(NetApi.class);
    Flowable flowable = Flowable.create(new FlowableOnSubscribe<String>() {

        @Override
        public void subscribe(@NonNull FlowableEmitter<String> flowableEmitter) throws Exception {
            String response = MainActivity.execute(api.getBaiduWeb());
            if (TextUtils.isEmpty(response)) {
                flowableEmitter.onError(new Exception());
                return;
            }
            flowableEmitter.onNext(response);
            flowableEmitter.onComplete();
        }
    }, BackpressureStrategy.LATEST).compose(bindUntilEvent(ActivityEvent.DESTROY)).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io());
    flowable.subscribe(new XXGSubscriber<String>() {

        @Override
        public void xxgNext(String o) {
            super.xxgNext(o);
            Log.e("TAG", "o = " + o);
        }

        @Override
        public void xxgError(Throwable t) {
            super.xxgError(t);
            Log.e("TAG", "t = " + t.getMessage());
        }

        @Override
        public void xxgComplete() {
            super.xxgComplete();
            Log.e("TAG", "Complete");
        }
    });
}
Also used : OkHttpClient(okhttp3.OkHttpClient) GenericDraweeHierarchy(com.facebook.drawee.generic.GenericDraweeHierarchy) DraweeController(com.facebook.drawee.interfaces.DraweeController) Headers(okhttp3.Headers) ApplicationInfo(android.content.pm.ApplicationInfo) Uri(android.net.Uri) PackageManager(android.content.pm.PackageManager) BaseControllerListener(com.facebook.drawee.controller.BaseControllerListener) NonNull(io.reactivex.annotations.NonNull) FlowableEmitter(io.reactivex.FlowableEmitter) Interceptor(okhttp3.Interceptor) StethoInterceptor(com.facebook.stetho.okhttp3.StethoInterceptor) RoundingParams(com.facebook.drawee.generic.RoundingParams) RequestBody(okhttp3.RequestBody) Buffer(okio.Buffer) FlowableOnSubscribe(io.reactivex.FlowableOnSubscribe) Request(okhttp3.Request) Handler(android.os.Handler) ControllerListener(com.facebook.drawee.controller.ControllerListener) BaseControllerListener(com.facebook.drawee.controller.BaseControllerListener) IOException(java.io.IOException) SimpleDraweeView(com.facebook.drawee.view.SimpleDraweeView) View(android.view.View) HttpUrl(okhttp3.HttpUrl) IOException(java.io.IOException) Response(retrofit2.Response) Retrofit(retrofit2.Retrofit) Animatable(android.graphics.drawable.Animatable) StethoInterceptor(com.facebook.stetho.okhttp3.StethoInterceptor) Nullable(javax.annotation.Nullable) Flowable(io.reactivex.Flowable)

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