Search in sources :

Example 51 with Builder

use of okhttp3.HttpUrl.Builder in project MyApp by MatthewDevelop.

the class ExampleUnitTest method APITest.

@Test
public void APITest() {
    String BASE_URL = "http://wanandroid.com/";
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    // 添加公共拦截器
    builder.addInterceptor(new CustomInterceptor());
    Retrofit retrofit = new Retrofit.Builder().client(builder.build()).baseUrl(BASE_URL).addCallAdapterFactory(RxJava2CallAdapterFactory.create()).addConverterFactory(GsonConverterFactory.create()).build();
    WanService movieService = retrofit.create(WanService.class);
    boolean test = true;
    if (test) {
    } else {
        movieService.getTagData().subscribe(new Observer<ResponseData<List<TypeTagVO>>>() {

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
            }

            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(ResponseData<List<TypeTagVO>> listResponseData) {
                System.out.println(listResponseData.toString());
            }
        });
        movieService.getHomeBannerList().subscribe(new Observer<ResponseData<List<BannerBean>>>() {

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onComplete() {
            }

            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(ResponseData<List<BannerBean>> listResponseData) {
                System.out.println(listResponseData.toString());
            }
        });
        movieService.getHomeArticleList(5).subscribe(new Observer<ResponseData<ArticleListVO>>() {

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
            }

            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(ResponseData<ArticleListVO> articleListVOResponseData) {
                System.out.println(articleListVOResponseData.toString());
            }
        });
    }
}
Also used : Disposable(io.reactivex.disposables.Disposable) OkHttpClient(okhttp3.OkHttpClient) ResponseData(cn.foxconn.matthew.myapp.wanandroid.bean.ResponseData) CustomInterceptor(cn.foxconn.matthew.myapp.wanandroid.helper.interceptor.CustomInterceptor) WanService(cn.foxconn.matthew.myapp.wanandroid.api.WanService) Retrofit(retrofit2.Retrofit) ArticleListVO(cn.foxconn.matthew.myapp.wanandroid.bean.pojovo.ArticleListVO) BannerBean(cn.foxconn.matthew.myapp.wanandroid.bean.pojo.BannerBean) TypeTagVO(cn.foxconn.matthew.myapp.wanandroid.bean.pojovo.TypeTagVO) List(java.util.List) Test(org.junit.Test)

Example 52 with Builder

use of okhttp3.HttpUrl.Builder in project MVPFrames by RockyQu.

the class AppConfiguration method applyOptions.

@Override
public void applyOptions(final Context context, AppConfigModule.Builder builder) {
    builder.httpUrl(Api.APP_DOMAIN).cacheFile(new File(ProjectUtils.CACHE)).networkHandler(new // Http全局响应结果的处理类
    NetworkHandler() {

        @Override
        public Request onHttpRequest(Interceptor.Chain chain, Request request) {
            // return chain.request().newBuilder().header("token", tokenId).build();
            return request;
        }

        @Override
        public Response onHttpResponse(String result, Interceptor.Chain chain, Request request, Response response) {
            return response;
        }
    }).interceptors(new Interceptor[] { new LoggingInterceptor(), new ParameterInterceptor(new ParameterInterceptor.ParameterCallback() {

        /**
         * 这里为接口添加类型为HashMap的统一参数,例如Token、版本号等。支持Get、Post方法,ParameterInterceptor会自动判断
         */
        @Override
        public HashMap<String, Object> parameters() {
            User user = (User) ((App) context).getAppComponent().extras().get(LoginActivity.class.getName());
            HashMap<String, Object> parameters = new HashMap<>();
            if (user != null) {
                // 为接口统一添加access_token参数
                parameters.put("access_token", user.getToken());
            }
            return parameters;
        }
    }) }).retrofitConfiguration(new // 扩展自定义配置Retrofit参数
    HttpModule.RetrofitConfiguration() {

        @Override
        public void configRetrofit(Context context, Retrofit.Builder builder) {
        }
    }).okHttpConfiguration(new // 扩展自定义配置OkHttp参数
    HttpModule.OkHttpConfiguration() {

        @Override
        public void configOkHttp(Context context, OkHttpClient.Builder builder) {
            builder.sslSocketFactory(SSL.createSSLSocketFactory(), new TrustAllX509TrustManager());
            builder.hostnameVerifier(new TrustAllHostnameVerifier());
        }
    }).gsonConfiguration(new // 扩展自定义配置Gson参数
    AppModule.GsonConfiguration() {

        @Override
        public void configGson(Context context, GsonBuilder builder) {
            builder.serializeNulls().registerTypeAdapter(ResponseEntity.class, new GsonResponseDeserializer());
        }
    }).cookieLoadForRequest(new PersistentCookieJar.CookieLoadForRequest() {

        @Override
        public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
        }

        @Override
        public List<Cookie> loadForRequest(List<Cookie> cookies) {
            return cookies;
        }
    });
}
Also used : User(com.frame.mvp.entity.User) OkHttpClient(okhttp3.OkHttpClient) HashMap(java.util.HashMap) GsonBuilder(com.google.gson.GsonBuilder) GsonResponseDeserializer(com.frame.mvp.app.utils.gson.GsonResponseDeserializer) TrustAllX509TrustManager(com.tool.common.http.ssl.TrustAllX509TrustManager) NetworkHandler(com.tool.common.http.NetworkHandler) List(java.util.List) ParameterInterceptor(com.tool.common.http.interceptor.ParameterInterceptor) Context(android.content.Context) Cookie(okhttp3.Cookie) LoggingInterceptor(com.tool.common.http.interceptor.LoggingInterceptor) GsonBuilder(com.google.gson.GsonBuilder) PersistentCookieJar(com.tool.common.http.cookie.PersistentCookieJar) Request(okhttp3.Request) HttpModule(com.tool.common.di.module.HttpModule) HttpUrl(okhttp3.HttpUrl) Response(okhttp3.Response) TrustAllHostnameVerifier(com.tool.common.http.ssl.TrustAllHostnameVerifier) File(java.io.File)

Example 53 with Builder

use of okhttp3.HttpUrl.Builder in project BaseProject by wareine.

the class UploadFileManager method upLoadFile.

/**
 *上传文件
 * @param actionUrl 接口地址
 * @param paramsMap 参数
 * @param callBack 回调
 * @param <T>
 */
public <T> void upLoadFile(String actionUrl, HashMap<String, Object> paramsMap, final ReqCallBack<T> callBack) {
    try {
        // 补全请求地址
        String requestUrl = String.format("%s/%s", BASE_URL, actionUrl);
        MultipartBody.Builder builder = new MultipartBody.Builder();
        // 设置类型
        builder.setType(MultipartBody.FORM);
        // 追加参数
        for (String key : paramsMap.keySet()) {
            Object object = paramsMap.get(key);
            if (!(object instanceof File)) {
                builder.addFormDataPart(key, object.toString());
            } else {
                File file = (File) object;
                builder.addFormDataPart(key, file.getName(), RequestBody.create(null, file));
            }
        }
        // 创建RequestBody
        RequestBody body = builder.build();
        // 创建Request
        final Request request = new Request.Builder().url(requestUrl).post(body).build();
        // 单独设置参数 比如读取超时时间
        final Call call = mOkHttpClient.newBuilder().writeTimeout(50, TimeUnit.SECONDS).build().newCall(request);
        call.enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, e.toString());
                failedCallBack("上传失败", callBack);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String string = response.body().string();
                    Log.e(TAG, "response ----->" + string);
                    successCallBack((T) string, callBack);
                } else {
                    failedCallBack("上传失败", callBack);
                }
            }
        });
    } catch (Exception e) {
        Log.e(TAG, e.toString());
    }
}
Also used : Call(okhttp3.Call) Request(okhttp3.Request) IOException(java.io.IOException) IOException(java.io.IOException) Response(okhttp3.Response) Callback(okhttp3.Callback) MultipartBody(okhttp3.MultipartBody) File(java.io.File) RequestBody(okhttp3.RequestBody)

Example 54 with Builder

use of okhttp3.HttpUrl.Builder in project BaseProject by wareine.

the class UploadFileManager method upLoadFile.

/**
 *上传文件
 * @param actionUrl 接口地址
 * @param paramsMap 参数
 * @param callBack 回调
 * @param <T>
 */
public <T> void upLoadFile(String actionUrl, HashMap<String, Object> paramsMap, final ReqProgressCallBack<T> callBack) {
    try {
        // 补全请求地址
        String requestUrl = String.format("%s/%s", BASE_URL, actionUrl);
        MultipartBody.Builder builder = new MultipartBody.Builder();
        // 设置类型
        builder.setType(MultipartBody.FORM);
        // 追加参数
        for (String key : paramsMap.keySet()) {
            Object object = paramsMap.get(key);
            if (!(object instanceof File)) {
                builder.addFormDataPart(key, object.toString());
            } else {
                File file = (File) object;
                builder.addFormDataPart(key, file.getName(), createProgressRequestBody(MEDIA_OBJECT_STREAM, file, callBack));
            }
        }
        // 创建RequestBody
        RequestBody body = builder.build();
        // 创建Request
        final Request request = new Request.Builder().url(requestUrl).post(body).build();
        final Call call = mOkHttpClient.newBuilder().writeTimeout(50, TimeUnit.SECONDS).build().newCall(request);
        call.enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, e.toString());
                failedCallBack("上传失败", callBack);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String string = response.body().string();
                    Log.e(TAG, "response ----->" + string);
                    successCallBack((T) string, callBack);
                } else {
                    failedCallBack("上传失败", callBack);
                }
            }
        });
    } catch (Exception e) {
        Log.e(TAG, e.toString());
    }
}
Also used : Call(okhttp3.Call) Request(okhttp3.Request) IOException(java.io.IOException) IOException(java.io.IOException) Response(okhttp3.Response) Callback(okhttp3.Callback) MultipartBody(okhttp3.MultipartBody) File(java.io.File) RequestBody(okhttp3.RequestBody)

Example 55 with Builder

use of okhttp3.HttpUrl.Builder in project BaseProject by wareine.

the class UploadFileManager method upLoadFile.

/**
 *上传文件
 * @param actionUrl 接口地址
 * @param paramsMap 参数
 * @param callBack 回调
 * @param <T>
 */
public <T> void upLoadFile(String actionUrl, HashMap<String, Object> paramsMap, final ReqProgressCallBack<T> callBack) {
    try {
        // 补全请求地址
        String requestUrl = String.format("%s/%s", BASE_URL, actionUrl);
        MultipartBody.Builder builder = new MultipartBody.Builder();
        // 设置类型
        builder.setType(MultipartBody.FORM);
        // 追加参数
        for (String key : paramsMap.keySet()) {
            Object object = paramsMap.get(key);
            if (!(object instanceof File)) {
                builder.addFormDataPart(key, object.toString());
            } else {
                File file = (File) object;
                builder.addFormDataPart(key, file.getName(), createProgressRequestBody(MEDIA_OBJECT_STREAM, file, callBack));
            }
        }
        // 创建RequestBody
        RequestBody body = builder.build();
        // 创建Request
        final Request request = new Request.Builder().url(requestUrl).post(body).build();
        final Call call = mOkHttpClient.newBuilder().writeTimeout(50, TimeUnit.SECONDS).build().newCall(request);
        call.enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, e.toString());
                failedCallBack("上传失败", callBack);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String string = response.body().string();
                    Log.e(TAG, "response ----->" + string);
                    successCallBack((T) string, callBack);
                } else {
                    failedCallBack("上传失败", callBack);
                }
            }
        });
    } catch (Exception e) {
        Log.e(TAG, e.toString());
    }
}
Also used : Call(okhttp3.Call) Request(okhttp3.Request) IOException(java.io.IOException) IOException(java.io.IOException) Response(okhttp3.Response) Callback(okhttp3.Callback) MultipartBody(okhttp3.MultipartBody) File(java.io.File) RequestBody(okhttp3.RequestBody)

Aggregations

Request (okhttp3.Request)206 Response (okhttp3.Response)148 OkHttpClient (okhttp3.OkHttpClient)142 IOException (java.io.IOException)111 RequestBody (okhttp3.RequestBody)81 Test (org.junit.Test)75 HttpUrl (okhttp3.HttpUrl)47 File (java.io.File)42 MockResponse (okhttp3.mockwebserver.MockResponse)42 MultipartBody (okhttp3.MultipartBody)40 Map (java.util.Map)39 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)31 Call (okhttp3.Call)29 Interceptor (okhttp3.Interceptor)29 Retrofit (retrofit2.Retrofit)29 Builder (okhttp3.OkHttpClient.Builder)26 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)25 ResponseBody (okhttp3.ResponseBody)24 HashMap (java.util.HashMap)22 FormBody (okhttp3.FormBody)21