使用nohttp的上传下载和get post请求1

package com.xjerp.xjtech.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.TextInputLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.xjerp.xjtech.R;
import com.xjerp.xjtech.activity.business.TradeActivity;
import com.xjerp.xjtech.adapter.BaseRecyclerAdapter;
import com.xjerp.xjtech.adapter.BaseRecyclerHolder;
import com.xjerp.xjtech.application.BaseActivity;
import com.xjerp.xjtech.bean.StaffBean;
import com.xjerp.xjtech.bean.YinLiBean;
import com.xjerp.xjtech.nohttp.CallSever;
import com.xjerp.xjtech.nohttp.HttpListener;
import com.xjerp.xjtech.utils.SharedPreferencesUtil;
import com.xjerp.xjtech.utils.ToastUtil;
import com.yanzhenjie.nohttp.FileBinary;
import com.yanzhenjie.nohttp.Headers;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.OnUploadListener;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.download.DownloadListener;
import com.yanzhenjie.nohttp.download.DownloadRequest;
import com.yanzhenjie.nohttp.rest.OnResponseListener;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.RequestQueue;
import com.yanzhenjie.nohttp.rest.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class TestNetworkActivity extends BaseActivity implements HttpListener {

    @BindView(R.id.name)
    EditText name;
    @BindView(R.id.input_name)
    TextInputLayout inputName;
    @BindView(R.id.pass)
    EditText pass;
    @BindView(R.id.input_pass)
    TextInputLayout inputPass;
    @BindView(R.id.login)
    Button login;
    @BindView(R.id.login2)
    Button login2;
    @BindView(R.id.topTitle)
    TextView topTitle;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.rl_food_list)
    RecyclerView rlFoodList;
    @BindView(R.id.staff_list)
    RecyclerView staffList;
    @BindView(R.id.jieguo)
    TextView jieguo;
    @BindView(R.id.jieguo2)
    TextView jieguo2;
    @BindView(R.id.pb)
    ProgressBar mProgressBar;

    private String username, password;
    private BaseRecyclerAdapter<YinLiBean> mFoodListAdapter;
    private List<YinLiBean> mFoodListDatas = new ArrayList<>();

    private BaseRecyclerAdapter<StaffBean> mStaffAdapter;
    private List<StaffBean> mStaffDatas = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_network);
        ButterKnife.bind(this);
        init();
    }

    @Override
    public void initView() {
        username = SharedPreferencesUtil.getString(this, "uid");
        initToolbar();
        ceShi2();

        initDownLoad();//初始化
        getFile();//初始化
    }

    @Override
    public void initData() {


        mStaffAdapter = new BaseRecyclerAdapter<StaffBean>(this, mStaffDatas, R.layout.item_network_recycle) {
            @Override
            public void convert(BaseRecyclerHolder holder, StaffBean item, int position, boolean isScrolling) {
                TextView tvDno = holder.getView(R.id.tv_food_num);
                tvDno.setText("编号:" + item.getG02());
                TextView tvName = holder.getView(R.id.tv_food_name);
                tvName.setText("名称:" + item.getG03());
                TextView tvPrice = holder.getView(R.id.tv_food_price);
                tvPrice.setText("时间:" + item.getG04());
                TextView tvDiscountPrice = holder.getView(R.id.tv_food_discount_price);
                tvDiscountPrice.setText("备注:" + item.getY04());
                ImageView imageView = holder.getView(R.id.iv_food);
//                Glide.with(TestNetworkActivity.this).load("" + item.getImg()).error(R.mipmap.icon).into(imageView);
            }
        };
        staffList.setLayoutManager(new LinearLayoutManager(this));
//        rlFoodList.setLayoutManager(new GridLayoutManager(this, 2, GridLayoutManager.VERTICAL, false));
        staffList.setAdapter(mStaffAdapter);
    }

    private DownloadRequest downloadRequest;//下载请求

    private static final String CancelSign = "CancelSign";


    private void check() {
        // 检查之前的下载状态
        int beforeStatus = downloadRequest.checkBeforeStatus();
        switch (beforeStatus) {
            case DownloadRequest.STATUS_RESTART:
                mProgressBar.setProgress(0);
                ToastUtil.showShort(this, "开始下载");
                break;
            case DownloadRequest.STATUS_RESUME:
                ToastUtil.showShort(this, "正在下载");
                break;
            case DownloadRequest.STATUS_FINISH:
                mProgressBar.setProgress(100);
                ToastUtil.showShort(this, "下载完成");
                break;
        }
    }
    private void stopDown() {
        downloadRequest.cancelBySign(CancelSign);//通过记号停止下载
    }

    private void goDown() {
        check();
        CallSever.getRequestInstance().download(6, downloadRequest, new DownloadListener() {
            @Override
            public void onDownloadError(int what, Exception exception) {
                //下载异常
                ToastUtil.showShort(TestNetworkActivity.this, "下载异常:" + exception.toString());

            }

            @Override
            public void onStart(int what, boolean isResume, long rangeSize, Headers responseHeaders, long allCount) {
                //开始下载
                //what
                //isResume 是否重新下载
                //rangeSize 已下载文件大小
                //responseHeaders
                //allCount 文件总大小
                //int progress = (int) (rangeSize * 100 / allCount); 下载进度
            }

            @Override
            public void onProgress(int what, int progress, long fileCount, long speed) {
                //下载进度
                //progress 进度
                //fileCount 文件大小
                System.out.println("----------------进度条"+progress);
                mProgressBar.setProgress(progress);
            }

            @Override
            public void onFinish(int what, String filePath) {
                //下载完成
                //filePath 文件路径
            }

            @Override
            public void onCancel(int what) {
                //下载取消
            }
        });

    }

    private void initDownLoad() {
        String getUrl = "http://gdown.baidu.com/data/wisegame/00d935b62e77cfc1/weixin_780.apk";
        downloadRequest = NoHttp.createDownloadRequest(getUrl,
                Environment.getExternalStorageDirectory().getPath(),
                "weiixn.apk",
                true,
                false);
        downloadRequest.setCancelSign(CancelSign);//设置停止下载的记号

    }

    private void ceShi() {
        String getUrl = "http://v.juhe.cn/laohuangli/d";
        //http://v.juhe.cn/laohuangli/d?date=2014-09-11&key=306cd3aeb988c3431e12eeb7813c699b
        Request<String> request = NoHttp.createStringRequest(getUrl);
        request.add("key", "306cd3aeb988c3431e12eeb7813c699b");
        request.add("date", "2014-09-12");

        //192.168.2.14:8080/xj/ApiTest
//        request.add("actionType", "listApiTest");
//        request.add("effective", "1");//MD5Util.getMd5Str(password)
//        request.add("search_g01", "1");
//        request.add("search_y01", "万筑1321");
//        request.add("search_y02", "3");
//        request.add("search_y06", "2");
//----------------保存设置--192.168.2.14:8080/xj/ApiTest?actionType=listApiTest&effective=1&search_g01=1&search_y01=%E4%B8%87%E7%AD%911321&search_y02=3&search_y06=2
        System.out.println("----------------url--" + request.getCacheKey());
        CallSever.getRequestInstance().add(this, 1, request, listener, false, true);


    }

    private void ceShi2() {
        String getUrl = "http://v.juhe.cn/weixin/query";
        // http://v.juhe.cn/weixin/query?key=c5e8f971956d0ca7229ec13d5a34849a&pno=2&ps=40
        //http://v.juhe.cn/laohuangli/d?date=2014-09-11&key=306cd3aeb988c3431e12eeb7813c699b
        Request<String> request = NoHttp.createStringRequest(getUrl);
        request.add("key", "c5e8f971956d0ca7229ec13d5a34849a");
        request.add("pno", "2");
        request.add("ps", "30");
        //192.168.2.14:8080/xj/ApiTest
//        request.add("actionType", "listApiTest");
//        request.add("effective", "1");//MD5Util.getMd5Str(password)
//        request.add("search_g01", "1");
//        request.add("search_y01", "万筑1321");
//        request.add("search_y02", "3");
//        request.add("search_y06", "2");
//----------------保存设置--192.168.2.14:8080/xj/ApiTest?actionType=listApiTest&effective=1&search_g01=1&search_y01=%E4%B8%87%E7%AD%911321&search_y02=3&search_y06=2
        System.out.println("----------------url--" + request.getCacheKey());
        CallSever.getRequestInstance().add(this, 2, request, listener, false, true);


    }

    private void ceShi3() {
        String getUrl = "http://v.juhe.cn/xhzd/query";
        //http://v.juhe.cn/xhzd/query?key=您申请的key&word=%E8%81%9A
        Request<String> request = NoHttp.createStringRequest(getUrl);
        request.add("key", "0be0dac62088651fc3fd1bac08b533fa");
        request.add("word", "");

        //192.168.2.14:8080/xj/ApiTest
//        request.add("actionType", "listApiTest");
//        request.add("effective", "1");//MD5Util.getMd5Str(password)
//        request.add("search_g01", "1");
//        request.add("search_y01", "万筑1321");
//        request.add("search_y02", "3");
//        request.add("search_y06", "2");
//----------------保存设置--192.168.2.14:8080/xj/ApiTest?actionType=listApiTest&effective=1&search_g01=1&search_y01=%E4%B8%87%E7%AD%911321&search_y02=3&search_y06=2
        System.out.println("----------------url--" + request.getCacheKey());
        CallSever.getRequestInstance().add(this, 1, request, listener, false, true);


    }

    private void ceShi6() {
        String geturl = "http://sh.qihoo.com/934e17a265f817ca7?uid=55fed8f7df90701cc2ecef37133c5d63&sign=360_79aabe15&scene=1&refer_scene=0";
        //创建NoHttp的请求对象,设置加载的网络路径和请求
//        Request<String> request = NoHttp.createStringRequest(geturl, RequestMethod.GET);

        String posturl = "http://www.sciencenet.cn/xml/iphoneinterface.aspx";
        //创建NoHttp的请求对象,设置加载的网络路径和请求
        Request<String> request = NoHttp.createStringRequest(posturl, RequestMethod.POST);
        request.add("type", "news");
        request.add("nums", "20");

        System.out.println("----------------请求体--" + request.getCacheKey());

        //获取核心的NoHttp网络工具类对象
        CallSever callServerInstance = CallSever.getRequestInstance();
        //把队列添加进去
        callServerInstance.add(TestNetworkActivity.this, 6, request, this, true, true);
    }

    private void ceShi7() {
        String getUrl = "https://www.jianshu.com/p/71e2e85cfee3";
        String postUrl = "http://192.168.3.107:8080/web/LoginServlet";
        //1.创建一个队列
        RequestQueue queue = NoHttp.newRequestQueue();
        Request<String> request = NoHttp.createStringRequest(getUrl, RequestMethod.GET);


//        //2.创建消息请求   参数1:String字符串,传网址  参数2:请求方式
//        Request<String> request = NoHttp.createStringRequest(postUrl, RequestMethod.POST);
//        //3.利用队列去添加消息请求
//        //使用request对象添加上传的对象添加键与值,post方式添加上传的数据
//        request.add("qq", "10000");
//        request.add("pwd", "abcde");
        queue.add(7, request, new OnResponseListener<String>() {
            @Override
            public void onStart(int what) {

            }

            @Override
            public void onSucceed(int what, Response<String> response) {
                jieguo2.setText(response.get() + "");
            }

            @Override
            public void onFailed(int what, Response<String> response) {
                Toast.makeText(TestNetworkActivity.this, "您的网络故障,请及时修复,在尝试", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFinish(int what) {

            }
        });
    }

    private File file;
    public ProgressDialog progressDialog;
    public String uploadurl = "http://192.168.27.27:8080/server/UpLoadServlet";//上传的服务器
    //assets目录下拿文件
    private void getFile() {
        try {
            file = new File(getFilesDir().getPath(),"firefox.exe");
            InputStream is = getAssets().open("firefox.exe");
            FileOutputStream fos = new FileOutputStream(file);
            int len =-1;
            byte[] buffer = new byte[1024];
            while ((len=is.read(buffer))!=-1) {
                fos.write(buffer, 0, len);
            }
            is.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    private void upLoad(){
        //2.创建一个请求。长传文件的话。请求方法必须是post
        Request<String> request = NoHttp.createStringRequest(uploadurl, RequestMethod.POST);
        //3.request请求添加提交的参数。
        FileBinary binary  = new FileBinary(file, "firefox.exe");
        System.out.println("----------------binary"+binary);
        //上传文件添加监听是在FileBinary中添加的。
        binary.setUploadListener(88, new OnUploadListener() {

            @Override
            public void onProgress(int what, int progress) {
                System.out.println("----------------onProgress"+progress);
                progressDialog.setProgress(progress);
            }

            @Override
            public void onStart(int what) {
                System.out.println("----------------onStart");
                progressDialog = new ProgressDialog(TestNetworkActivity.this);
                progressDialog.setTitle("上传中。。。");
                progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                progressDialog.setMax(100);
                progressDialog.show();
            }

            @Override
            public void onFinish(int what) {
                System.out.println("----------------onFinish");
                progressDialog.dismiss();
            }

            @Override
            public void onError(int what, Exception exception) {
                System.out.println("----------------onError");
            }

            @Override
            public void onCancel(int what) {
                System.out.println("----------------onCancel");
            }
        });
        request.add("file",binary);
        //4.添加请求队列

        CallSever.getRequestInstance().request(99, request, responseListener);

    }
    OnResponseListener<String> responseListener = new OnResponseListener<String>() {
        @Override
        public void onStart(int what) {
            // System.out.println("onStart");
        }

        @Override
        public void onSucceed(int what, Response<String> response) {
            // System.out.println("onSucceed");
            ToastUtil.showShort(TestNetworkActivity.this, "上传成功:" + response.toString());

        }

        @Override
        public void onFailed(int what, Response<String> response) {
            // System.out.println("onFailed");
            ToastUtil.showShort(TestNetworkActivity.this, "上传失败:" + response.toString());

        }

        @Override
        public void onFinish(int what) {
            // System.out.println("onFinish");
        }
    };


    private void initToolbar() {
        topTitle.setText("测试");
        toolbar.setTitle("");
//        toolbar.setLogo(R.drawable.ic_launcher);
        setSupportActionBar(toolbar);
        getSupportActionBar().setHomeButtonEnabled(false);
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void showListView() {
        mFoodListAdapter = new BaseRecyclerAdapter<YinLiBean>(this, mFoodListDatas, R.layout.item_network_recycle) {
            @Override
            public void convert(BaseRecyclerHolder holder, YinLiBean item, int position, boolean isScrolling) {
                TextView tvDno = holder.getView(R.id.tv_food_num);
                tvDno.setText("编号:" + item.id);
                TextView tvName = holder.getView(R.id.tv_food_name);
                tvName.setText("名称:" + item.title);
                TextView tvPrice = holder.getView(R.id.tv_food_price);
                tvPrice.setText("价格:" + item.source);
                TextView tvDiscountPrice = holder.getView(R.id.tv_food_discount_price);
                tvDiscountPrice.setText("折扣价:" + item.source);
                ImageView imageView = holder.getView(R.id.iv_food);
                Glide.with(TestNetworkActivity.this).load("" + item.firstImg).error(R.mipmap.ic_launcher).into(imageView);
            }
        };
//        rlFoodList.setLayoutManager(new LinearLayoutManager(this));
        rlFoodList.setLayoutManager(new GridLayoutManager(this, 2, GridLayoutManager.VERTICAL, false));
        rlFoodList.setAdapter(mFoodListAdapter);
    }

    HttpListener<String> listener = new HttpListener<String>() {
        @Override
        public void onSucceed(int what, Response<String> response) {
            switch (what) {
                case 0:
                    if (TextUtils.isEmpty(response.get())) {
                        ToastUtil.showShort(TestNetworkActivity.this, "登录失败");
                    } else {
                        try {
                            JSONObject object = new JSONObject(response.get());
                            if (object.getBoolean("success")) {
                                SharedPreferencesUtil.putString(TestNetworkActivity.this, "phone", object.has("phone") ? object.getString("phone") : "");
                                SharedPreferencesUtil.putString(TestNetworkActivity.this, "password", password);
                                //eid
                                SharedPreferencesUtil.putString(TestNetworkActivity.this, "id", object.has("id") ? object.getString("id") : "");
                                SharedPreferencesUtil.putString(TestNetworkActivity.this, "userlogo", object.has("userlogo") ? object.getString("userlogo") : "");
                                SharedPreferencesUtil.putString(TestNetworkActivity.this, "shoplogo", object.has("shoplogo") ? object.getString("shoplogo") : "");
                                SharedPreferencesUtil.putString(TestNetworkActivity.this, "shopname", object.has("shopname") ? object.getString("shopname") : "");
                                SharedPreferencesUtil.putString(TestNetworkActivity.this, "address", object.has("address") ? object.getString("address") : "");
                                //手机号
                                SharedPreferencesUtil.putString(TestNetworkActivity.this, "uid", object.has("uid") ? object.getString("uid") : "");
                                SharedPreferencesUtil.putString(TestNetworkActivity.this, "username", object.has("username") ? object.getString("username") : "");
                                SharedPreferencesUtil.putString(TestNetworkActivity.this, "shopid", object.has("shopid") ? object.getString("shopid") : "");
                                SharedPreferencesUtil.putString(TestNetworkActivity.this, "authorityContent", object.has("authorityContent") ? object.getString("authorityContent") : "");
                                startActivity(new Intent(TestNetworkActivity.this, MainActivity.class));
//                                turnActivity(MainActivity.class);
                                TestNetworkActivity.this.finish();
                            } else {
                                ToastUtil.showShort(TestNetworkActivity.this, "登录失败");

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    break;
                case 2:
                    try {
                        JSONObject jsonObject = new JSONObject(response.get());


                        if (jsonObject.getInt("error_code") == 0) {
                            JSONObject data = jsonObject.getJSONObject("result");
                            int pagecount = data.getInt("ps") + data.getInt("pno") + data.getInt("totalPage");
                            // Integer.valueOf(data.getString("pagecount"));
                            Toast.makeText(TestNetworkActivity.this, pagecount + "", Toast.LENGTH_SHORT).show();

                            if (!data.getString("list").equals("null")) {
                                JSONArray ja = data.getJSONArray("list");
                                for (int i = 0; i < ja.length(); i++) {
                                    YinLiBean bean = new YinLiBean();
                                    bean.id = ja.getJSONObject(i).getString("id");
                                    bean.source = ja.getJSONObject(i).getString("source");
                                    bean.title = ja.getJSONObject(i).getString("title");
                                    bean.firstImg = ja.getJSONObject(i).getString("firstImg");
                                    mFoodListDatas.add(bean);
                                }
                                showListView();
                            }
                        } else {
                            Toast.makeText(TestNetworkActivity.this, "连接超时", Toast.LENGTH_SHORT)
                                    .show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;

                case 1:
                    try {


                        int responseCode = response.getHeaders().getResponseCode();// 服务器响应码
                        System.out.println("----------------保存设置1--" + responseCode);
                        if (responseCode == 200) {

                        }
                        System.out.println("----------------保存设置2--" + response.get());
                        //----------------保存设置2--{"reason":"successed","result":{"id":"1657","yangli":"2014-09-11","yinli":"甲午()年八月十八","wuxing":"井泉水 建执位","chongsha":"冲兔(己卯)煞东","baiji":"乙不栽植千株不长 酉不宴客醉坐颠狂","jishen":"官日 六仪 益後 月德合 除神 玉堂 鸣犬","yi":"祭祀 出行 扫舍 馀事勿取","xiongshen":"月建 小时 土府 月刑 厌对 招摇 五离","ji":"诸事不宜"},"error_code":0}
                        JSONObject jsonObject = new JSONObject(response.get());

                        JSONObject jsObject = jsonObject.getJSONObject("result");
                        String aaa = jsObject.getString("jishen");

                        System.out.println("----------------数据--" + aaa.toString());
                        jieguo2.setText(jsObject.getString("xiongshen"));
//                            mFoodListAdapter.notifyDataSetChanged();


                        if ("true".equals(jsonObject.getString("success"))) {
//                            String array = jsonObject.getString("data");
//                            Gson gson = new Gson();
//                            List<StaffBean> data = gson.fromJson(array, new TypeToken<List<StaffBean>>() {
//                            }.getType());
//                            mStaffDatas.addAll(data);
//                            mFoodListAdapter.notifyDataSetChanged();
//                        }

//                        JSONArray jsonArray = jsonObject.getJSONArray("rows");
//                        System.out.println("------"+jsonArray.length());
//                        if (jsonArray != null) {
//                            for (int i = 0; i < jsonArray.length(); i++) {
//                                StaffBean cBean = new StaffBean();
//                                cBean.g02 = jsonArray.getJSONObject(i).getString("g02");
//                                cBean.g03 = jsonArray.getJSONObject(i).getString("g03");
//                                cBean.g04 = jsonArray.getJSONObject(i).getString("g04");
//                                cBean.y04 = jsonArray.getJSONObject(i).getString("y04");
//                                mStaffDatas.add(cBean);
//                            }
//
//                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
            }
        }

        @Override
        public void onFailed(int what, Response<String> response) {

        }
    };


    @OnClick({R.id.login, R.id.login2,R.id.login3,R.id.login4,R.id.jieguo})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.login:
                Intent intent2 = new Intent(TestNetworkActivity.this, TradeActivity.class);
                startActivity(intent2);
                username = inputName.getEditText().getText().toString();
                password = inputPass.getEditText().getText().toString();
                if ("".equals(username)) {
                    inputName.setError("用户名不能为空");
                    inputName.setErrorEnabled(true);
                } else {
                    inputName.setError(null);
                    inputName.setErrorEnabled(false);
                }
                if ("".equals(pass)) {
                    inputPass.setError("密码不能为空");
                    inputPass.setErrorEnabled(true);
                } else {
                    inputPass.setError(null);
                    inputPass.setErrorEnabled(false);
                }
                //LoadingDialog.make(this).setMessage("登录中...").show();
                Request<String> request = NoHttp.createStringRequest("192.168.2.14:8080/xj/ApiTest");
                request.add("actionType", "listApiTest");
                request.add("effective", "1");//MD5Util.getMd5Str(password)
                request.add("search_g01", "1");
                request.add("search_y01", "万筑1321");
                request.add("search_y02", "3");
                request.add("search_y06", "2");

                //www.baidu.com?uname=&pwd=e10adc3949ba59abbe56e057f20f883e&ctrl=ask&action=login&module=baction
                System.out.println("----------------保存设置--" + request.getCacheKey());
                CallSever.getRequestInstance().add(this, 0, request, listener, false, true);
                break;
            case R.id.login2:
                Intent intent = new Intent(TestNetworkActivity.this, TestRefreshctivity.class);
                startActivity(intent);
                break;
            case R.id.login3:
                goDown();
                break;
            case R.id.login4:
//                stopDown();
                upLoad();
                break;
            case R.id.jieguo:
                //        ceShi6();
        //        ceShi();
        //        ceShi7();
                break;
        }
    }

    @Override
    public void onSucceed(int what, Response response) {
        switch (what) {
            case 6:
                jieguo2.setText(response.get() + "");
                break;
            default:
                break;
        }
    }

    @Override
    public void onFailed(int what, Response response) {

    }

}

NoHttp 是专门做Android网络请求与下载的框架。支持HTTP/HTTPS,自动维持Cookie,异步/同步请求,大文件/多文件上传,文件下载;支持304缓存,302/303重定向,支持代理服务器。NoHttp特性:支持HTTP/HTTPS,自动维持Cookie,异步/同步请求,大文件/多文件上传,文件下载,上传下载均有进度。支持304缓存,自定义缓存,302/303重定向,支持代理服务器访问地址(如: Google)。NoHttp是队列,自动为请求排队,可以取消指定请求, 可以取消队列所有请求,亦可以停止队列。支持请求String、Bitmap、Json、JavaBean,可自定义扩展请求类型。Request对象包涵参数、文件、请求头等;Response对象包涵响应内容,响应头等信息,Cookie。使用Gradle构建时添加依赖:// 引用最新版 compile 'com.yolanda.nohttp:nohttp: ' // 或则引用指定版本 compile 'com.yolanda.nohttp:nohttp:1.0.0'一. 请求1.请求String数据// 请求对象 Request request = NoHttp.createStringRequest(url, requestMethod); //添加请求头 request.addHeader("AppVersioin", "2.0"); // 添加请求参数 request.add("userName", "yolanda"); //上传文件 request.add("file", new FileBinary(file)); ...2.请求Json数据// JsonObject Request request = NoHttp.createJsonObjectRequest(url, reqeustMethod); queue.add(what, request, responseListener); … // JsonArray Request request = NoHttp.createJsonArrayRequest(url, reqeustMethod); queue.add(what, request, responseListener);3. 请求Bitmap数据Request request = NoHttp.createImageRequest(url, requestMethod); ...4. 取消请求取消单个请求Request request = NoHttp.createStringRequest(url); ... request.cancel();从队列中取消指定的请求Request request = NoHttp.createStringRequest(url); request.setCancelSign(sign); … queue.cancelBySign(sign);取消队列中所有请求queue.cancelAll();停止队列RequestQueue queue = NoHttp.newRequestQueue(); ... queue.stop();5. 同步请求// 在当前线程发起请求,在线程这么使用 Request request = NoHttp.createStringRequest(url); Response response = NoHttp.startRequestSync(request); if (response.isSucceed()) {     // 请求成功 } else {     // 请求失败 }二. 缓存1. Http标准协议的缓存,比如响应码是304时现在很多公司使用了RESTFUL风格来写Http API,所以这个是必须有的。Request request = NoHttp.createJsonObjectRequest(url); // NoHttp本身是RESTFUL风格的标准Http协议,所以这里不用设置或者设置为DEFAULT request.setCacheMode(CacheMode.DEFAULT); ...2.请求服务器失败的时候,读取缓存Request request = NoHttp.createJsonObjectRequest(url); // 非标准Http协议,改变缓存模式为REQUEST_FAILED_READ_CACHE request.setCacheMode(CacheMode.REQUEST_FAILED_READ_CACHE); ...3. 如果发现有缓存直接成功,没有缓存才请求服务器我们知道ImageLoader的核心除了内存优化外,剩下一个就是发现把内地有图片则直接使用,没有则请求服务器,所以NoHttp这一点非常使用做一个ImageLoader。Request request = NoHttp.createJsonObjectRequest(url); // 非标准Http协议,改变缓存模式为IF_NONE_CACHE_REQUEST request.setCacheMode(CacheMode.IF_NONE_CACHE_REQUEST); ...请求图片,缓存图片。// 如果没有缓存才去请求服务器,否则使用缓存,缓存图片演示 Request request = NoHttp.createImageRequest(imageUrl); request.setCacheMode(CacheMode.IF_NONE_CACHE_REQUEST); ...4. 仅仅读取缓存Request request = NoHttp.createJsonObjectRequest(url); // 非标准Http协议,改变缓存模式为ONLY_READ_CACHE request.setCacheMode(CacheMode.ONLY_READ_CACHE); ...注意:缓存不管是String、Json、图片还是任何请求都可以被NoHttp缓存二、响应OnResponseListener responseListener = new OnResponseListener() {     @Override     public void onStart(int what) {         // 请求开始时,可以显示一个Dialog     }     @Override     public void onFinish(int what) {         // 请求接受时,关闭Dialog     }     @Override     public void onSucceed(int what, Response response) {         // 接受请求结果         String result = response.get();         // Bitmap imageHead = response.get(); // 如果是bitmap类型,都是同样的用法     }     @Override     public void onFailed(int what, String url, Object tag, Exception exception, ...) {         // 请求失败或者发生异常         // 这里根据exception处理不同的错误,比如超时、网络不好等     } };三. 自定义请求类型: FastJsonRequest1.定义请求对象public class FastJsonRequest extends RestRequestor { public FastJsonRequest(String url) {     super(url); } public FastJsonRequest(String url, RequestMethod requestMethod) {     super(url, requestMethod); } @Override public JSONObject parseResponse(String url, Headers headers, byte[] responseBody) {     String result = StringRequest.parseResponseString(url, headers, responseBody);     JSONObject jsonObject = null;     if (!TextUtils.isEmpty(result)) {         jsonObject = JSON.parseObject(result);     } else {         // 这里默认的错误可以定义为你们自己的数据格式         jsonObject = JSON.toJSON("{}");     }     return jsonObject; } @Override public String getAccept() {     // 告诉服务器你接受什么类型的数据, 会添加到请求头的Accept中     return "application/json;q=1"; } }2.使用自定义请求-NoHttp默认请求没有区别Request mRequest = new FastJsonRequest(url, requestMethod); queue.add(what, mRequest, responseListener);五. 下载文件发起下载请求//下载文件 downloadRequest = NoHttp.createDownloadRequest(url, fielDir, fileName, true, false); // what 区分下载 // downloadRequest 下载请求对象 // downloadListener 下载监听 CallServer.getDownloadInstance().add(0, downloadRequest, downloadListener);暂停或者停止下载downloadRequest.cancel();监听下载过程private DownloadListener downloadListener = new DownloadListener() {     @Override     public void onStart(int what, boolean resume, long preLenght, Headers header, long count) {     }     @Override     public void onProgress(int what, int progress, long downCount) {         // 更新下载进度     }     @Override     public void onFinish(int what, String filePath) {     }     @Override     public void onDownloadError(int what, StatusCode code, CharSequence message) {     }     @Override     public void onCancel(int what) {     } }; 标签:NoHttp
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值