OKHTTP使用 保存session

项目资源地址:http://download.youkuaiyun.com/download/weixin_40391500/10123640
/get请求/

private OkHttpClient client = new OkHttpClient();
private long OUT_TIME = 10;

public void sendRequest(String url, final CallBacks callbacks) {
        String JSESSIONID = (String) SPUtils.get(MyApplication.context, Constants.session, "");
        //头部添加session
        final Request request = new Request.Builder().addHeader("cookie", JSESSIONID).url(url).build();
        client.newBuilder().connectTimeout(OUT_TIME, TimeUnit.SECONDS)
                .readTimeout(OUT_TIME,TimeUnit.SECONDS)
                .writeTimeout(OUT_TIME,TimeUnit.SECONDS)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callbacks.onError(e.toString());
            }

            //解析成功
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response != null && response.isSuccessful()) {
                    //获取session,session改变替换之前的session并保存
                    String session = response.headers().get("Set-Cookie");
                    if (!StringUtils.isEmptyNull(session)){
                        String JSESSIONID = session.substring(0, session.indexOf(";"));
                        String Cokiet = (String) SPUtils.get(MyApplication.context, Constants.session, "");
                        if (!JSESSIONID.equals(Cokiet)){
                            SPUtils.set(MyApplication.context, Constants.session, JSESSIONID);
                        }
                    }
                    callbacks.onSuccess(response.body().string());
                }else {
                    callbacks.onError(response.toString());
                }
            }
        });
    }

/post表单请求/

public void sendRequest(String url, Map<String, String> params,
            final CallBacks callbacks) {
        // 表单对象,包含input开始的操作
        FormBody.Builder from = new FormBody.Builder();
        // 键值对不为空,他的值也不为空
        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                // 装载表单值
                from.add(entry.getKey(), entry.getValue());
            }
        }
        RequestBody body = from.build();
        String JSESSIONID = (String) SPUtils.get(MyApplication.context, Constants.session, "");
        // post提交
        Request request = new Request.Builder().addHeader("cookie", JSESSIONID).url(url).post(body).build();
        client.newBuilder().connectTimeout(OUT_TIME, TimeUnit.SECONDS)
                .readTimeout(OUT_TIME,TimeUnit.SECONDS)
                .writeTimeout(OUT_TIME,TimeUnit.SECONDS)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callbacks.onError(e.toString());
            }

            @Override
            public void onResponse(Call call, Response response)
                    throws IOException {
                if (response != null && response.isSuccessful()) {
                    callbacks.onSuccess(response.body().string());
                }else {
                callbacks.onError(response.toString());
            }
            }
        });
    }

/*下载文件*/

public void downFile(String url, final CallBacks callbacks){
        Request request = new Request.Builder().url(url).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callbacks.onError(e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    InputStream in = response.body().byteStream();
                    File file = new File(SaveFileUtils.dir_driver_img);
                    if (!file.exists()){
                        file.mkdirs();
                    }
                    FileOutputStream os = new FileOutputStream(new File(file, SignData.getIntance().selete().getSertify() + ".jpg"));
                    byte []buffer = new byte[2048];
                    int len;
                    while ((len = in.read(buffer)) != -1){
                        os.write(buffer, 0, len);
                    }
                    in.close();
                    os.flush();
                    MyApplication.dialogFlag = false;
                    callbacks.onSuccess("");
                }catch (IOException e){
                    MyApplication.dialogFlag = false;
                    callbacks.onError(e.toString());
                    LogUtils.saveFileToSMB(e.getMessage());
                    e.printStackTrace();
                }
            }
        });
    }

/*上传文件*/

public void uploadFile(String url, Map<String, String> map, final CallBacks callbacks){
        File file;
        RequestBody requestBody;
        MultipartBody.Builder multipart = new MultipartBody.Builder().setType(MultipartBody.FORM);
        for (Map.Entry<String, String> entry :map.entrySet()) {
            file = new File(entry.getValue());
            if (file.exists()){
                requestBody = RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), file);
                multipart.addFormDataPart("file", entry.getKey(), requestBody);
            }
        }
        Request request = new Request.Builder().post(multipart.build()).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callbacks.onError(e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                callbacks.onSuccess(response.body().string());
            }
        });
    }

/get请求url拼接/

public String getUrl(String url, HashMap<String, String> map){
        StringBuffer sb = new StringBuffer();
        sb.append(url+"?");
        if (map == null) return sb.toString();
        for (Map.Entry<String, String> entry :map.entrySet()) {
            sb.append(entry.getKey()+"=").append(entry.getValue()+"&");
        }
        sb.deleteCharAt(sb.toString().length()-1);
        return sb.toString();
    }

/判断网络是否可用*/

public static boolean isConnectionAvailable(Context cotext){
        boolean isConnectionFail = true;
        ConnectivityManager connectivityManager = (ConnectivityManager)cotext.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager != null){
            NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
            if (activeNetworkInfo == null || !activeNetworkInfo.isConnected()){
                isConnectionFail = true;
            }else{
                isConnectionFail = false;
            }
        }else{
            isConnectionFail = false;
        }
        return isConnectionFail;
    }

项目资源地址:http://download.youkuaiyun.com/download/weixin_40391500/10123640

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值