Java Code Examples for com.zhy.http.okhttp.OkHttpUtils

The following examples show how to use com.zhy.http.okhttp.OkHttpUtils. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: Socket.io-FLSocketIM-Android   Source File: App.java    License: MIT License 6 votes vote down vote up
private void initOkHttpUtil () {

        CookieJarImpl cookieJar = new CookieJarImpl(new PersistentCookieStore(getApplicationContext()));
        OkHttpClient client = new OkHttpClient.Builder()
                .connectionPool(new ConnectionPool(5, 5, TimeUnit.MINUTES))
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {

                        Request request = chain.request();
                        request = request.newBuilder().addHeader("Connection", "keep-alive").build();
                        return chain.proceed(request);
                    }
                })
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .cookieJar(cookieJar)
                .build();
        OkHttpUtils.initClient(client);
    }
 
Example 2
Source Project: fitness_Android   Source File: NewsDetailActivity.java    License: Apache License 2.0 6 votes vote down vote up
private void addNewComment() {
    String commentText = addCommentET.getText().toString().trim();
    if (TextUtils.isEmpty(commentText)) {
        DisplayToast("请先输入内容");
        return;
    }
    String url = Constants.BASE_URL + "Comment?method=addNewComment";
    OkHttpUtils
            .post()
            .url(url)
            .id(3)
            .addParams("newsId", newsId + "")
            .addParams("userId", Constants.USER.getUserId() + "")
            .addParams("comment", commentText)
            .addParams("replyUser", replyUsername)
            .build()
            .execute(new MyStringCallback());
}
 
Example 3
Source Project: ClassSchedule   Source File: app.java    License: Apache License 2.0 6 votes vote down vote up
private void initOkHttp() {
    ClearableCookieJar cookieJar =
            new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(getApplicationContext()));

    Cache.instance().setCookieJar(cookieJar);

    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            //.followRedirects(false)  //禁制OkHttp的重定向操作,我们自己处理重定向
            .followSslRedirects(false)
            //.cookieJar(new LocalCookieJar())   //为OkHttp设置自动携带Cookie的功能
            .addInterceptor(new LoggerInterceptor("TAG"))
            //.cookieJar(new CookieJarImpl(new PersistentCookieStore(getBaseContext()))) //要在内存Cookie前
            //.cookieJar(new CookieJarImpl(new MemoryCookieStore()))//内存Cookie
            .cookieJar(cookieJar)
            .cache(null)
            .build();
    OkHttpUtils.initClient(okHttpClient);
}
 
Example 4
Source Project: enjoyshop   Source File: PostFormRequest.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected RequestBody wrapRequestBody(RequestBody requestBody, final Callback callback)
{
    if (callback == null) return requestBody;
    CountingRequestBody countingRequestBody = new CountingRequestBody(requestBody, new CountingRequestBody.Listener()
    {
        @Override
        public void onRequestProgress(final long bytesWritten, final long contentLength)
        {

            OkHttpUtils.getInstance().getDelivery().execute(new Runnable()
            {
                @Override
                public void run()
                {
                    callback.inProgress(bytesWritten * 1.0f / contentLength,contentLength,id);
                }
            });

        }
    });
    return countingRequestBody;
}
 
Example 5
Source Project: enjoyshop   Source File: PostFileRequest.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected RequestBody wrapRequestBody(RequestBody requestBody, final Callback callback)
{
    if (callback == null) return requestBody;
    CountingRequestBody countingRequestBody = new CountingRequestBody(requestBody, new CountingRequestBody.Listener()
    {
        @Override
        public void onRequestProgress(final long bytesWritten, final long contentLength)
        {

            OkHttpUtils.getInstance().getDelivery().execute(new Runnable()
            {
                @Override
                public void run()
                {
                    callback.inProgress(bytesWritten * 1.0f / contentLength,contentLength,id);
                }
            });

        }
    });
    return countingRequestBody;
}
 
Example 6
Source Project: enjoyshop   Source File: OtherRequest.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected Request buildRequest(RequestBody requestBody)
{
    if (method.equals(OkHttpUtils.METHOD.PUT))
    {
        builder.put(requestBody);
    } else if (method.equals(OkHttpUtils.METHOD.DELETE))
    {
        if (requestBody == null)
            builder.delete();
        else
            builder.delete(requestBody);
    } else if (method.equals(OkHttpUtils.METHOD.HEAD))
    {
        builder.head();
    } else if (method.equals(OkHttpUtils.METHOD.PATCH))
    {
        builder.patch(requestBody);
    }

    return builder.build();
}
 
Example 7
Source Project: enjoyshop   Source File: RequestCall.java    License: Apache License 2.0 6 votes vote down vote up
public Call buildCall(Callback callback)
{
    request = generateRequest(callback);

    if (readTimeOut > 0 || writeTimeOut > 0 || connTimeOut > 0)
    {
        readTimeOut = readTimeOut > 0 ? readTimeOut : OkHttpUtils.DEFAULT_MILLISECONDS;
        writeTimeOut = writeTimeOut > 0 ? writeTimeOut : OkHttpUtils.DEFAULT_MILLISECONDS;
        connTimeOut = connTimeOut > 0 ? connTimeOut : OkHttpUtils.DEFAULT_MILLISECONDS;

        clone = OkHttpUtils.getInstance().getOkHttpClient().newBuilder()
                .readTimeout(readTimeOut, TimeUnit.MILLISECONDS)
                .writeTimeout(writeTimeOut, TimeUnit.MILLISECONDS)
                .connectTimeout(connTimeOut, TimeUnit.MILLISECONDS)
                .build();

        call = clone.newCall(request);
    } else
    {
        call = OkHttpUtils.getInstance().getOkHttpClient().newCall(request);
    }
    return call;
}
 
Example 8
Source Project: iMoney   Source File: OklaClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
     * initialize okhttp client config
     *
     * @param context
     */
    private void initOkhttpClient(Context context) {
        if (context == null) return;
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10000L, TimeUnit.MILLISECONDS)
                .readTimeout(10000L, TimeUnit.MILLISECONDS)
//                .dns(OkHttpDns.getInstance(context))
//                .hostnameVerifier(new HostnameVerifier() {
//                    @Override
//                    public boolean verify(String hostname, SSLSession session) {
//                        return hostname.contains("domain.com");// 替换为自己api的域名
//                    }
//                })
//                .sslSocketFactory(getSSLSocketFactory())
                .build();

        OkHttpUtils.initClient(okHttpClient);
    }
 
Example 9
Source Project: OpenEyes   Source File: MyApplication.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    Fresco.initialize(this);
    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectionSpecs(Arrays.asList(
                    ConnectionSpec.MODERN_TLS,
                    ConnectionSpec.COMPATIBLE_TLS,
                    ConnectionSpec.CLEARTEXT))
            .addInterceptor(new LoggerInterceptor("==http"))
            .connectTimeout(10000L, TimeUnit.MILLISECONDS)
            .readTimeout(10000L, TimeUnit.MILLISECONDS)
            .build();

    OkHttpUtils.initClient(okHttpClient);
}
 
Example 10
Source Project: okhttputils   Source File: PostFormRequest.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected RequestBody wrapRequestBody(RequestBody requestBody, final Callback callback)
{
    if (callback == null) return requestBody;
    CountingRequestBody countingRequestBody = new CountingRequestBody(requestBody, new CountingRequestBody.Listener()
    {
        @Override
        public void onRequestProgress(final long bytesWritten, final long contentLength)
        {

            OkHttpUtils.getInstance().getDelivery().execute(new Runnable()
            {
                @Override
                public void run()
                {
                    callback.inProgress(bytesWritten * 1.0f / contentLength,contentLength,id);
                }
            });

        }
    });
    return countingRequestBody;
}
 
Example 11
Source Project: okhttputils   Source File: PostFileRequest.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected RequestBody wrapRequestBody(RequestBody requestBody, final Callback callback)
{
    if (callback == null) return requestBody;
    CountingRequestBody countingRequestBody = new CountingRequestBody(requestBody, new CountingRequestBody.Listener()
    {
        @Override
        public void onRequestProgress(final long bytesWritten, final long contentLength)
        {

            OkHttpUtils.getInstance().getDelivery().execute(new Runnable()
            {
                @Override
                public void run()
                {
                    callback.inProgress(bytesWritten * 1.0f / contentLength,contentLength,id);
                }
            });

        }
    });
    return countingRequestBody;
}
 
Example 12
Source Project: okhttputils   Source File: OtherRequest.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected Request buildRequest(RequestBody requestBody)
{
    if (method.equals(OkHttpUtils.METHOD.PUT))
    {
        builder.put(requestBody);
    } else if (method.equals(OkHttpUtils.METHOD.DELETE))
    {
        if (requestBody == null)
            builder.delete();
        else
            builder.delete(requestBody);
    } else if (method.equals(OkHttpUtils.METHOD.HEAD))
    {
        builder.head();
    } else if (method.equals(OkHttpUtils.METHOD.PATCH))
    {
        builder.patch(requestBody);
    }

    return builder.build();
}
 
Example 13
Source Project: okhttputils   Source File: RequestCall.java    License: Apache License 2.0 6 votes vote down vote up
public Call buildCall(Callback callback)
{
    request = generateRequest(callback);

    if (readTimeOut > 0 || writeTimeOut > 0 || connTimeOut > 0)
    {
        readTimeOut = readTimeOut > 0 ? readTimeOut : OkHttpUtils.DEFAULT_MILLISECONDS;
        writeTimeOut = writeTimeOut > 0 ? writeTimeOut : OkHttpUtils.DEFAULT_MILLISECONDS;
        connTimeOut = connTimeOut > 0 ? connTimeOut : OkHttpUtils.DEFAULT_MILLISECONDS;

        clone = OkHttpUtils.getInstance().getOkHttpClient().newBuilder()
                .readTimeout(readTimeOut, TimeUnit.MILLISECONDS)
                .writeTimeout(writeTimeOut, TimeUnit.MILLISECONDS)
                .connectTimeout(connTimeOut, TimeUnit.MILLISECONDS)
                .build();

        call = clone.newCall(request);
    } else
    {
        call = OkHttpUtils.getInstance().getOkHttpClient().newCall(request);
    }
    return call;
}
 
Example 14
Source Project: okhttputils   Source File: MainActivity.java    License: Apache License 2.0 6 votes vote down vote up
public void postFile(View view)
{
    File file = new File(Environment.getExternalStorageDirectory(), "messenger_01.png");
    if (!file.exists())
    {
        Toast.makeText(MainActivity.this, "文件不存在,请修改文件路径", Toast.LENGTH_SHORT).show();
        return;
    }
    String url = mBaseUrl + "user!postFile";
    OkHttpUtils
            .postFile()
            .url(url)
            .file(file)
            .build()
            .execute(new MyStringCallback());


}
 
Example 15
Source Project: okhttputils   Source File: MainActivity.java    License: Apache License 2.0 6 votes vote down vote up
public void multiFileUpload(View view)
{
    File file = new File(Environment.getExternalStorageDirectory(), "messenger_01.png");
    File file2 = new File(Environment.getExternalStorageDirectory(), "test1#.txt");
    if (!file.exists())
    {
        Toast.makeText(MainActivity.this, "文件不存在,请修改文件路径", Toast.LENGTH_SHORT).show();
        return;
    }
    Map<String, String> params = new HashMap<>();
    params.put("username", "张鸿洋");
    params.put("password", "123");

    String url = mBaseUrl + "user!uploadFile";
    OkHttpUtils.post()//
            .addFile("mFile", "messenger_01.png", file)//
            .addFile("mFile", "test1.txt", file2)//
            .url(url)
            .params(params)//
            .build()//
            .execute(new MyStringCallback());
}
 
Example 16
Source Project: OpenWeatherPlus-Android   Source File: AppNetConfig.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * post请求
 *
 * @param url
 * @param params
 * @param headers  请求头是非必传字段,如果没有,设置null即可
 * @param callback
 */
public static final void RequestPost(final String url, final HashMap<String, String> params,
                                     final HashMap<String, String> headers, final StringCallback callback) {
    if ( headers == null ) {
        OkHttpUtils.post().url(url).params(params).build().execute(callback);
    } else {
        OkHttpUtils.post().url(url).headers(headers).params(params).build().execute(callback);
    }
}
 
Example 17
Source Project: OpenWeatherPlus-Android   Source File: AppNetConfig.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * post请求
 *
 * @param url
 * @param params
 * @param headers  请求头是非必传字段,如果没有,设置null即可
 * @param callback
 */
public static final void RequestPost(final String url, final int writeTimeOut, final HashMap<String, String> params,
                                     final HashMap<String, String> headers, final StringCallback callback) {
    if ( headers == null ) {
        OkHttpUtils.post().url(url).params(params).build().readTimeOut(writeTimeOut).execute(callback);
    } else {
        OkHttpUtils.post().url(url).headers(headers).params(params).build().readTimeOut(writeTimeOut).execute(callback);
    }
}
 
Example 18
Source Project: renrenpay-android   Source File: NetHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 用户注册
 * /api/register
 */
public static void userRegister(String userName, String password, String name, String code, HttpResHandler handler) {
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append(httpHeader);
    stringBuffer.append("/register");
    String registerPassword = Md5Utils.encode(password);
    OkHttpUtils.post().url(stringBuffer.toString()).addParams("phone", userName)
            .addParams("password", registerPassword).build().execute(handler);
}
 
Example 19
Source Project: renrenpay-android   Source File: NetHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取salt
 * /api/users/salt
 */
public static void getSalt(String phone, HttpResHandler handler) {
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append(httpHeader);
    stringBuffer.append("/api/users/salt");
    OkHttpUtils.get().url(stringBuffer.toString()).addParams("mobile_phone", phone).build().execute(handler);
}
 
Example 20
Source Project: renrenpay-android   Source File: NetHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 用户登陆
 * /api2/login
 */
public static void userLogin(String phone, String password, HttpResHandler handler) {
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append(httpHeader);
    stringBuffer.append("/api2/phone/login");
    OkHttpUtils.post().url(stringBuffer.toString()).addParams("mobile_phone", phone)
            .addParams("password", password).build().execute(handler);
}
 
Example 21
Source Project: renrenpay-android   Source File: NetHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 完善用户资料
 * /api/user/modify
 */
public static void modifyUserInfo(String nickName, String address, String wechart, String website, String e_mail, HttpResHandler handler) {
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append(httpHeader);
    stringBuffer.append("/user/modify");
    OkHttpUtils.post().url(stringBuffer.toString()).addParams("nick_name", nickName)
            .addParams("address", address).addParams("wechart", wechart)
            .addParams("website", website).addParams("e_mail", e_mail)
            .addHeader("token", appContext.getUser().getToken()).build().execute(handler);
}
 
Example 22
Source Project: renrenpay-android   Source File: NetHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取应用列表
 * /api2/phone/query_app
 */
public static void getAppList(HttpResHandler handler) {
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append(httpHeader);
    stringBuffer.append("/api2/phone/query_app");
    OkHttpUtils.post().url(stringBuffer.toString())
            .addHeader("token", appContext.getUser().getToken()).build().execute(handler);
}
 
Example 23
Source Project: renrenpay-android   Source File: NetHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取app详情
 * /api/app/info
 */
public static void getAppInfo(String appId, HttpResHandler handler) {
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append(httpHeader);
    stringBuffer.append("/app/info");
    OkHttpUtils.get().url(stringBuffer.toString()).addParams("app_id", appId)
            .addHeader("token", appContext.getUser().getToken()).build().execute(handler);
}
 
Example 24
Source Project: renrenpay-android   Source File: NetHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 发生二维码
 * /api2/phone/get_qrcode
 */
public static void receivePayCode(String codeUrl, String orderId, String appId, int amount, int payWay, String payCode, String order_userid, HttpResHandler handler) {
    Log.d("cxy", "token -> " + appContext.getUser().getToken());
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append(httpHeader);
    stringBuffer.append("/api2/phone/get_qrcode");
    OkHttpUtils.post().url(stringBuffer.toString()).addParams("qrcode", codeUrl)
            .addParams("appid", appId).addParams("orderid", orderId)
            .addParams("amount", amount + "").addParams("payway", payWay + "")
            .addParams("pay_code", payCode).addParams("userid", order_userid)
            .addHeader("token", appContext.getUser().getToken()).build().execute(handler);
}
 
Example 25
Source Project: renrenpay-android   Source File: NetHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 支付成功通知
 * /api2/phone/pay_success
 */
public static void paySuccessNotify(int pay_way, int amount, String pay_code, String transid, HttpResHandler handler) {
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append(httpHeader);
    stringBuffer.append("/api2/phone/pay_success");
    OkHttpUtils.post().url(stringBuffer.toString())
            .addParams("amount", amount + "").addParams("payway", pay_way + "")
            .addParams("pay_code", pay_code).addParams("transid", transid)
            .addHeader("token", appContext.getUser().getToken()).build().execute(handler);
}
 
Example 26
Source Project: renrenpay-android   Source File: NetHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 查询收款列表
 * /api2/phone/paychecks_list
 */
public static void paycheckList(int page, int pageSize, HttpResHandler handler) {
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append(httpHeader);
    stringBuffer.append("/api2/phone/paychecks_list");
    OkHttpUtils.get().url(stringBuffer.toString())
            .addParams("page", page + "").addParams("page_size", pageSize + "").addParams("state", "1")
            .addHeader("token", appContext.getUser().getToken()).build().execute(handler);
}
 
Example 27
Source Project: renrenpay-android   Source File: NetHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 上传日志
 * /api2/phone/set_logs
 */
public static void paySetLogs(String logs, HttpResHandler handler) {
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append(httpHeader);
    stringBuffer.append("/api2/phone/set_logs");
    OkHttpUtils.post().url(stringBuffer.toString())
            .addParams("list", logs + "")
            .addHeader("token", appContext.getUser().getToken()).build().execute(handler);
}
 
Example 28
Source Project: renrenpay-android   Source File: NetHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 清除微信付款码
 * /api2/phone/clear_wx
 * */
public static void clearWxPayCode(HttpResHandler handler) {
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append(httpHeader);
    stringBuffer.append("/api2/phone/clear_wx");
    OkHttpUtils.post().url(stringBuffer.toString())
            .addHeader("token", appContext.getUser().getToken()).build().execute(handler);
}
 
Example 29
Source Project: fitness_Android   Source File: FoundFragment.java    License: Apache License 2.0 5 votes vote down vote up
private void reLoadNews() {
    String url = Constants.BASE_URL + "News?method=getNewsList";
    OkHttpUtils
            .post()
            .url(url)
            .id(1)
            .build()
            .execute(new MyStringCallback());
}
 
Example 30
Source Project: fitness_Android   Source File: MeFragment.java    License: Apache License 2.0 5 votes vote down vote up
private void getRecords() {
    String url = Constants.BASE_URL + "DailyCheck?method=getHomepageTotalRecord";
    OkHttpUtils
            .post()
            .url(url)
            .addParams("userId", Constants.USER.getUserId() + "")
            .id(1)
            .build()
            .execute(new MyStringCallback());
}