自定义的网络框架

来源:互联网 发布:自动编程软件 编辑:程序博客网 时间:2024/06/06 01:34
<span style="font-size:14px;">/** * 对外提供业务工厂 * Created by DangF on 2016/6/8. */public class PublicBusinessFactory implements IPublicBusinessFactory {    private static PublicBusinessFactory businessFactory;    private Context context;    private PublicBusinessFactory(Context context) {        this.context = context;    }    public static PublicBusinessFactory getInstance(Context context) {        if (businessFactory == null) {            businessFactory = new PublicBusinessFactory(context);        }        return businessFactory;    }    @Override    public IMultiPublicBusiness getMultiBusiness() {        return new LetvPlayServiceBusiness(context);//        return new ImplPublicBusiness();    }}</span>


/** * 对外提供业务工厂 * Created by DangF on 2016/6/8. */public interface IPublicBusinessFactory {    /**     * 获取对外提供业务类(乐视)     *     * @return     */    IMultiPublicBusiness getMultiBusiness();}


/** * 对外提供接口(乐视播放业务) * Created by DangF on 2016/6/7. */public interface IMultiPublicBusiness {    /**     * 收藏列表(获取作品列表)     * @param start     * @param length     * @param type     * @param callBack     */    void getCollectionList(int userid, int type, int start, int length, BusinessCallBack<LetvCollectionListResult> callBack);    /**     * 历史记录(下载记录)     * @param start     * @param length     * @param type     * @param callBack     */    void getHistoryList(int start, int length,int type, BusinessCallBack<LetvHistoryResult> callBack);}


<span style="font-size:14px;">/** * 对外提供接口(乐视播放业务) * */public class LetvPlayServiceBusiness implements IMultiPublicBusiness {    private IHttpManager httpManager;    private Context context;    public LetvPlayServiceBusiness(Context context) {        this.context = context;        httpManager = HttpFactory.getInstance(context).getKaraokeHttpManager();    }    /**     * 收藏列表(获取作品列表)     * @param userid     * @param type     * @param start     * @param length     * @param callBack     *     */    @Override    public void getCollectionList(int userid, int type, int start, int length, BusinessCallBack<LetvCollectionListResult> callBack) {        TypeReference<LetvCollectionListResult> typeReference = new TypeReference<LetvCollectionListResult>(){        };        HttpRequestParams params = new HttpRequestParams();        params.put("userid",userid );        params.put("type", 0);        params.put("start",start);        params.put("length",length);        httpManager.request(context, "/tian/ugc/getMvList.action", params, typeReference, callBack, KaraokeHttpManager.METHOD_GET);    }    /**     * 历史记录(下载记录)     * @param start     * @param length     * @param type     * @param callBack     */    @Override    public void getHistoryList(int start, int length, int type, BusinessCallBack<LetvHistoryResult> callBack) {        TypeReference<LetvHistoryResult> typeReference = new TypeReference<LetvHistoryResult>(){        };        HttpRequestParams params = new HttpRequestParams();        params.put("start", start);        params.put("length", length);        params.put("type", 0);        httpManager.request(context, "/tian/ugc/getMyDownList.action", params, typeReference, callBack, KaraokeHttpManager.METHOD_GET);    }}</span>

/*上传:request={    <common>,            "userid":4460310    "type":1 // 0:全部 1:独唱作品 2:合唱作品 3:发起的合唱 4:转发 5:独唱作品+合唱作品    "start":0, //第一次获取最新内容为0,刷最新内容为当前第一条记录id,翻页时为最后一条记    "length":100}*/private void test3() {    BusinessFactory.getInstance(this).getPublicBusinessFactory().getMultiBusiness().getCollectionList(52893537,0,0,30, new BusinessCallBack<LetvCollectionListResult>() {        @Override        public void onResult(Result<LetvCollectionListResult> t) {            System.out.print(" getCollectionList onResult " + t.getResult().getList());        }    });}/*上传:request={    <common>,            start:1,            length:20,            type:1// 0表示作品;1表示合唱伴奏;2:曲库歌曲下载}*/private void test2() {    BusinessFactory.getInstance(this).getPublicBusinessFactory().getMultiBusiness().getHistoryList(0, 100, 0, new BusinessCallBack<LetvHistoryResult>() {        @Override        public void onResult(Result<LetvHistoryResult> t) {            System.out.print(" getCollectionList onResult " + t.getResult().getUgc());        }    });}

public class LetvCollectionListResult /*extends BaseBusinessResult implements LetvCollectionListModel*/ {    /**     * price : 0     * id : 3441098     * name : 爱要坦荡荡     * res_name : 爱要坦荡荡     * size : 1870454     * filterKey : AYTDD     * date : 2014-07-30 14:12:05     * content : FM201.3人声乐团《爱要坦荡荡》非完成版~阿卡贝拉~     * playNum : 11189     * flowerNum : 1918     * commentNum : 283     * forwardNum : 64     * downNum : 4     * mark : 0     * istop : 0     * startRecord : 0.441179     * duration : 111     * type : 1     * clientDate : 2014-07-30 14:10:46     * pwd_type : 0     * up_type : 0     * icon : http://file6.audiocn.org/web/images/mvicon/audio.png?t=1     * shareurl : http://www.tlkg.com.cn/maiba/share.action2?code=TVY7MzQ0MTA5OA==     * show_user :     * resolving :     * image : http://fxcdn6.audiocn.com/upload_files/images/360_270/20140730/c3a3f33c-6de3-4f43-85a7-16ae635604a8.jpg     * activityScore : 0     * song : {"id":2}     * chorusSong : {"id":0}     * playUrl : http://www.tlkg.com.cn/ugcp/play.kg?mvid=3441098     * user : {"id":52893537,"attest":0,"nickname":"杏☪⋆  ","headImage":"http://fxcdn9.audiocn.com/upload_files/images/360_270/20150804/04c3944d-13e7-46dd-876b-32db3023f045.jpg","cover":"http://fxcdn9.audiocn.com/upload_files/images/640_480/20150830/2b55fea6-ebd3-428a-b479-e3d14af74a6c.jpg","sex":2,"hot_num":589573,"level":65,"nick_pindex":"X","attestUrl":"","title":"4","constellations":"3","introduction":"","exp":205232,"birthday":"1990-01-01","groupTips":""}     * editTips : 0     */    private List<ListBean> list;    public List<ListBean> getList() {        return list;    }    public void setList(List<ListBean> list) {        this.list = list;    }    public static class ListBean {        private int price;        private int id;        private String name;        private String res_name;        private int size;        private String filterKey;        private String date;        private String content;        private int playNum;        private int flowerNum;        private int commentNum;        private int forwardNum;        private int downNum;        private int mark;        private int istop;        private String startRecord;        private String duration;        private int type;        private String clientDate;        private int pwd_type;        private int up_type;        private String icon;        private String shareurl;        private String show_user;        private String resolving;        private String image;        private int activityScore;        /**         * id : 2         */        private SongBean song;        /**         * id : 0         */        private ChorusSongBean chorusSong;        private String playUrl;        /**         * id : 52893537         * attest : 0         * nickname : 杏☪⋆         * headImage : http://fxcdn9.audiocn.com/upload_files/images/360_270/20150804/04c3944d-13e7-46dd-876b-32db3023f045.jpg         * cover : http://fxcdn9.audiocn.com/upload_files/images/640_480/20150830/2b55fea6-ebd3-428a-b479-e3d14af74a6c.jpg         * sex : 2         * hot_num : 589573         * level : 65         * nick_pindex : X         * attestUrl :         * title : 4         * constellations : 3         * introduction :         * exp : 205232         * birthday : 1990-01-01         * groupTips :         */        private UserBean user;        private int editTips;        public int getPrice() {            return price;        }        public void setPrice(int price) {            this.price = price;        }        public int getId() {            return id;        }        public void setId(int id) {            this.id = id;        }        public String getName() {            return name;        }        public void setName(String name) {            this.name = name;        }        public String getRes_name() {            return res_name;        }        public void setRes_name(String res_name) {            this.res_name = res_name;        }        public int getSize() {            return size;        }        public void setSize(int size) {            this.size = size;        }        public String getFilterKey() {            return filterKey;        }        public void setFilterKey(String filterKey) {            this.filterKey = filterKey;        }        public String getDate() {            return date;        }        public void setDate(String date) {            this.date = date;        }        public String getContent() {            return content;        }        public void setContent(String content) {            this.content = content;        }        public int getPlayNum() {            return playNum;        }        public void setPlayNum(int playNum) {            this.playNum = playNum;        }        public int getFlowerNum() {            return flowerNum;        }        public void setFlowerNum(int flowerNum) {            this.flowerNum = flowerNum;        }        public int getCommentNum() {            return commentNum;        }        public void setCommentNum(int commentNum) {            this.commentNum = commentNum;        }        public int getForwardNum() {            return forwardNum;        }        public void setForwardNum(int forwardNum) {            this.forwardNum = forwardNum;        }        public int getDownNum() {            return downNum;        }        public void setDownNum(int downNum) {            this.downNum = downNum;        }        public int getMark() {            return mark;        }        public void setMark(int mark) {            this.mark = mark;        }        public int getIstop() {            return istop;        }        public void setIstop(int istop) {            this.istop = istop;        }        public String getStartRecord() {            return startRecord;        }        public void setStartRecord(String startRecord) {            this.startRecord = startRecord;        }        public String getDuration() {            return duration;        }        public void setDuration(String duration) {            this.duration = duration;        }        public int getType() {            return type;        }        public void setType(int type) {            this.type = type;        }        public String getClientDate() {            return clientDate;        }        public void setClientDate(String clientDate) {            this.clientDate = clientDate;        }        public int getPwd_type() {            return pwd_type;        }        public void setPwd_type(int pwd_type) {            this.pwd_type = pwd_type;        }        public int getUp_type() {            return up_type;        }        public void setUp_type(int up_type) {            this.up_type = up_type;        }        public String getIcon() {            return icon;        }        public void setIcon(String icon) {            this.icon = icon;        }        public String getShareurl() {            return shareurl;        }        public void setShareurl(String shareurl) {            this.shareurl = shareurl;        }        public String getShow_user() {            return show_user;        }        public void setShow_user(String show_user) {            this.show_user = show_user;        }        public String getResolving() {            return resolving;        }        public void setResolving(String resolving) {            this.resolving = resolving;        }        public String getImage() {            return image;        }        public void setImage(String image) {            this.image = image;        }        public int getActivityScore() {            return activityScore;        }        public void setActivityScore(int activityScore) {            this.activityScore = activityScore;        }        public SongBean getSong() {            return song;        }        public void setSong(SongBean song) {            this.song = song;        }        public ChorusSongBean getChorusSong() {            return chorusSong;        }        public void setChorusSong(ChorusSongBean chorusSong) {            this.chorusSong = chorusSong;        }        public String getPlayUrl() {            return playUrl;        }        public void setPlayUrl(String playUrl) {            this.playUrl = playUrl;        }        public UserBean getUser() {            return user;        }        public void setUser(UserBean user) {            this.user = user;        }        public int getEditTips() {            return editTips;        }        public void setEditTips(int editTips) {            this.editTips = editTips;        }        public static class SongBean {            private int id;            public int getId() {                return id;            }            public void setId(int id) {                this.id = id;            }        }        public static class ChorusSongBean {            private int id;            public int getId() {                return id;            }            public void setId(int id) {                this.id = id;            }        }        public static class UserBean {            private int id;            private int attest;            private String nickname;            private String headImage;            private String cover;            private int sex;            private int hot_num;            private int level;            private String nick_pindex;            private String attestUrl;            private String title;            private String constellations;            private String introduction;            private int exp;            private String birthday;            private String groupTips;            public int getId() {                return id;            }            public void setId(int id) {                this.id = id;            }            public int getAttest() {                return attest;            }            public void setAttest(int attest) {                this.attest = attest;            }            public String getNickname() {                return nickname;            }            public void setNickname(String nickname) {                this.nickname = nickname;            }            public String getHeadImage() {                return headImage;            }            public void setHeadImage(String headImage) {                this.headImage = headImage;            }            public String getCover() {                return cover;            }            public void setCover(String cover) {                this.cover = cover;            }            public int getSex() {                return sex;            }            public void setSex(int sex) {                this.sex = sex;            }            public int getHot_num() {                return hot_num;            }            public void setHot_num(int hot_num) {                this.hot_num = hot_num;            }            public int getLevel() {                return level;            }            public void setLevel(int level) {                this.level = level;            }            public String getNick_pindex() {                return nick_pindex;            }            public void setNick_pindex(String nick_pindex) {                this.nick_pindex = nick_pindex;            }            public String getAttestUrl() {                return attestUrl;            }            public void setAttestUrl(String attestUrl) {                this.attestUrl = attestUrl;            }            public String getTitle() {                return title;            }            public void setTitle(String title) {                this.title = title;            }            public String getConstellations() {                return constellations;            }            public void setConstellations(String constellations) {                this.constellations = constellations;            }            public String getIntroduction() {                return introduction;            }            public void setIntroduction(String introduction) {                this.introduction = introduction;            }            public int getExp() {                return exp;            }            public void setExp(int exp) {                this.exp = exp;            }            public String getBirthday() {                return birthday;            }            public void setBirthday(String birthday) {                this.birthday = birthday;            }            public String getGroupTips() {                return groupTips;            }            public void setGroupTips(String groupTips) {                this.groupTips = groupTips;            }        }    }}

public class LetvHistoryResult/* extends BaseBusinessResult*//* implements LetvHistoryModel*/ {    /**     * price : 0     * id : 38016     * name : 芊芊     * res_name : 芊芊     * size : 15242101     * filterKey : QQ     * date : 2012-11-09 23:02:29     * content :     * playNum : 8320     * flowerNum : 10279     * commentNum : 117     * forwardNum : 1     * downNum : 10     * mark : 0     * istop : 0     * startRecord : nan     * duration : 231     * type : 0     * clientDate :     * pwd_type : 0     * up_type : 0     * icon : http://file6.audiocn.org/web/images/mvicon/video.png     * shareurl : http://www.tlkg.com.cn/maiba/share.action2?code=TVY7MzgwMTY=     * show_user :     * resolving : 999     * image : http://fxcdn6.audiocn.com/upload_files/images/360_270/20140730/cb4381a3-0d6e-4420-b6bb-d4986a5b49d6.jpg     * activityScore : 0     * song : {"id":388167}     * chorusSong : {"id":0}     * playUrl : http://www.tlkg.com.cn/ugcp/play.kg?mvid=38016     * user : {"id":52893537,"attest":0,"nickname":"杏☪⋆ ","headImage":"http://fxcdn9.audiocn.com/upload_files/images/360_270/20150804/04c3944d-13e7-46dd-876b-32db3023f045.jpg","cover":"http://fxcdn9.audiocn.com/upload_files/images/640_480/20150830/2b55fea6-ebd3-428a-b479-e3d14af74a6c.jpg","sex":2,"hot_num":589573,"level":65,"nick_pindex":"X","attestUrl":"","title":"4","constellations":"3","introduction":"","exp":205232,"birthday":"1990-01-01","groupTips":""}     */    private Ugc ugc;    /**     * ugc : {"price":0,"id":38016,"name":"芊芊","res_name":"芊芊","size":15242101,"filterKey":"QQ","date":"2012-11-09 23:02:29","content":"","playNum":8320,"flowerNum":10279,"commentNum":117,"forwardNum":1,"downNum":10,"mark":0,"istop":0,"startRecord":"nan","duration":"231","type":0,"clientDate":"","pwd_type":0,"up_type":0,"icon":"http://file6.audiocn.org/web/images/mvicon/video.png","shareurl":"http://www.tlkg.com.cn/maiba/share.action2?code=TVY7MzgwMTY=","show_user":"","resolving":"999","image":"http://fxcdn6.audiocn.com/upload_files/images/360_270/20140730/cb4381a3-0d6e-4420-b6bb-d4986a5b49d6.jpg","activityScore":0,"song":{"id":388167},"chorusSong":{"id":0},"playUrl":"http://www.tlkg.com.cn/ugcp/play.kg?mvid=38016","user":{"id":52893537,"attest":0,"nickname":"杏☪⋆ ","headImage":"http://fxcdn9.audiocn.com/upload_files/images/360_270/20150804/04c3944d-13e7-46dd-876b-32db3023f045.jpg","cover":"http://fxcdn9.audiocn.com/upload_files/images/640_480/20150830/2b55fea6-ebd3-428a-b479-e3d14af74a6c.jpg","sex":2,"hot_num":589573,"level":65,"nick_pindex":"X","attestUrl":"","title":"4","constellations":"3","introduction":"","exp":205232,"birthday":"1990-01-01","groupTips":""}}     * id : 226     * time : 2012-12-27 21:13:15     */    private int id;    private String time;    public Ugc getUgc() {        return ugc;    }    public void setUgc(Ugc ugc) {        this.ugc = ugc;    }    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getTime() {        return time;    }    public void setTime(String time) {        this.time = time;    }    public static class Ugc {        private int price;        private int id;        private String name;        private String res_name;        private int size;        private String filterKey;        private String date;        private String content;        private int playNum;        private int flowerNum;        private int commentNum;        private int forwardNum;        private int downNum;        private int mark;        private int istop;        private String startRecord;        private String duration;        private int type;        private String clientDate;        private int pwd_type;        private int up_type;        private String icon;        private String shareurl;        private String show_user;        private String resolving;        private String image;        private int activityScore;        /**         * id : 388167         */        private SongBean song;        /**         * id : 0         */        private ChorusSongBean chorusSong;        private String playUrl;        /**         * id : 52893537         * attest : 0         * nickname : 杏☪⋆         * headImage : http://fxcdn9.audiocn.com/upload_files/images/360_270/20150804/04c3944d-13e7-46dd-876b-32db3023f045.jpg         * cover : http://fxcdn9.audiocn.com/upload_files/images/640_480/20150830/2b55fea6-ebd3-428a-b479-e3d14af74a6c.jpg         * sex : 2         * hot_num : 589573         * level : 65         * nick_pindex : X         * attestUrl :         * title : 4         * constellations : 3         * introduction :         * exp : 205232         * birthday : 1990-01-01         * groupTips :         */        private User user;        public int getPrice() {            return price;        }        public void setPrice(int price) {            this.price = price;        }        public int getId() {            return id;        }        public void setId(int id) {            this.id = id;        }        public String getName() {            return name;        }        public void setName(String name) {            this.name = name;        }        public String getRes_name() {            return res_name;        }        public void setRes_name(String res_name) {            this.res_name = res_name;        }        public int getSize() {            return size;        }        public void setSize(int size) {            this.size = size;        }        public String getFilterKey() {            return filterKey;        }        public void setFilterKey(String filterKey) {            this.filterKey = filterKey;        }        public String getDate() {            return date;        }        public void setDate(String date) {            this.date = date;        }        public String getContent() {            return content;        }        public void setContent(String content) {            this.content = content;        }        public int getPlayNum() {            return playNum;        }        public void setPlayNum(int playNum) {            this.playNum = playNum;        }        public int getFlowerNum() {            return flowerNum;        }        public void setFlowerNum(int flowerNum) {            this.flowerNum = flowerNum;        }        public int getCommentNum() {            return commentNum;        }        public void setCommentNum(int commentNum) {            this.commentNum = commentNum;        }        public int getForwardNum() {            return forwardNum;        }        public void setForwardNum(int forwardNum) {            this.forwardNum = forwardNum;        }        public int getDownNum() {            return downNum;        }        public void setDownNum(int downNum) {            this.downNum = downNum;        }        public int getMark() {            return mark;        }        public void setMark(int mark) {            this.mark = mark;        }        public int getIstop() {            return istop;        }        public void setIstop(int istop) {            this.istop = istop;        }        public String getStartRecord() {            return startRecord;        }        public void setStartRecord(String startRecord) {            this.startRecord = startRecord;        }        public String getDuration() {            return duration;        }        public void setDuration(String duration) {            this.duration = duration;        }        public int getType() {            return type;        }        public void setType(int type) {            this.type = type;        }        public String getClientDate() {            return clientDate;        }        public void setClientDate(String clientDate) {            this.clientDate = clientDate;        }        public int getPwd_type() {            return pwd_type;        }        public void setPwd_type(int pwd_type) {            this.pwd_type = pwd_type;        }        public int getUp_type() {            return up_type;        }        public void setUp_type(int up_type) {            this.up_type = up_type;        }        public String getIcon() {            return icon;        }        public void setIcon(String icon) {            this.icon = icon;        }        public String getShareurl() {            return shareurl;        }        public void setShareurl(String shareurl) {            this.shareurl = shareurl;        }        public String getShow_user() {            return show_user;        }        public void setShow_user(String show_user) {            this.show_user = show_user;        }        public String getResolving() {            return resolving;        }        public void setResolving(String resolving) {            this.resolving = resolving;        }        public String getImage() {            return image;        }        public void setImage(String image) {            this.image = image;        }        public int getActivityScore() {            return activityScore;        }        public void setActivityScore(int activityScore) {            this.activityScore = activityScore;        }        public SongBean getSong() {            return song;        }        public void setSong(SongBean song) {            this.song = song;        }        public ChorusSongBean getChorusSong() {            return chorusSong;        }        public void setChorusSong(ChorusSongBean chorusSong) {            this.chorusSong = chorusSong;        }        public String getPlayUrl() {            return playUrl;        }        public void setPlayUrl(String playUrl) {            this.playUrl = playUrl;        }        public User getUser() {            return user;        }        public void setUser(User user) {            this.user = user;        }        public static class SongBean {            private int id;            public int getId() {                return id;            }            public void setId(int id) {                this.id = id;            }        }        public static class ChorusSongBean {            private int id;            public int getId() {                return id;            }            public void setId(int id) {                this.id = id;            }        }        public static class User {            private int id;            private int attest;            private String nickname;            private String headImage;            private String cover;            private int sex;            private int hot_num;            private int level;            private String nick_pindex;            private String attestUrl;            private String title;            private String constellations;            private String introduction;            private int exp;            private String birthday;            private String groupTips;            public int getId() {                return id;            }            public void setId(int id) {                this.id = id;            }            public int getAttest() {                return attest;            }            public void setAttest(int attest) {                this.attest = attest;            }            public String getNickname() {                return nickname;            }            public void setNickname(String nickname) {                this.nickname = nickname;            }            public String getHeadImage() {                return headImage;            }            public void setHeadImage(String headImage) {                this.headImage = headImage;            }            public String getCover() {                return cover;            }            public void setCover(String cover) {                this.cover = cover;            }            public int getSex() {                return sex;            }            public void setSex(int sex) {                this.sex = sex;            }            public int getHot_num() {                return hot_num;            }            public void setHot_num(int hot_num) {                this.hot_num = hot_num;            }            public int getLevel() {                return level;            }            public void setLevel(int level) {                this.level = level;            }            public String getNick_pindex() {                return nick_pindex;            }            public void setNick_pindex(String nick_pindex) {                this.nick_pindex = nick_pindex;            }            public String getAttestUrl() {                return attestUrl;            }            public void setAttestUrl(String attestUrl) {                this.attestUrl = attestUrl;            }            public String getTitle() {                return title;            }            public void setTitle(String title) {                this.title = title;            }            public String getConstellations() {                return constellations;            }            public void setConstellations(String constellations) {                this.constellations = constellations;            }            public String getIntroduction() {                return introduction;            }            public void setIntroduction(String introduction) {                this.introduction = introduction;            }            public int getExp() {                return exp;            }            public void setExp(int exp) {                this.exp = exp;            }            public String getBirthday() {                return birthday;            }            public void setBirthday(String birthday) {                this.birthday = birthday;            }            public String getGroupTips() {                return groupTips;            }            public void setGroupTips(String groupTips) {                this.groupTips = groupTips;            }        }    }}

/** * 执行网络请求,解析数据并下发 * Created by DangF on 2016/5/18. */public class KaraokeHttpManager implements IHttpManager {    public static final int METHOD_GET = 0;    public static final int METHOD_POST = 1;    private static final String TAG = "KaraokeHttpManager";    private static KaraokeHttpManager manager = null;    private IHttpRequest serverRequest;    private Handler mHandler = new Handler();    public static KaraokeHttpManager getInstance(Context context) {        if (manager == null) {            manager = new KaraokeHttpManager(context);        }        return manager;    }    private KaraokeHttpManager(Context context) {        serverRequest = new KaraokeServerRequest(context);        Karaoke.init(context, 0, 0);    }    public <I, T extends I> void request(Context context, String url, HttpRequestParams params, TypeReference<T> typeToken, BusinessCallBack<I> callBack) {        request(context, url, params, typeToken, null, null, callBack, METHOD_POST);    }    public <I, T extends I> void request(Context context, String url, HttpRequestParams params, TypeReference<T> typeToken, BusinessCallBack<I> callBack, int method) {        request(context, url, params, typeToken, null, null, callBack, method);    }    public <I, T extends I, M> void request(final Context context, final String url, final HttpRequestParams params, final TypeReference<T> typeTokenT, final TypeReference<M> typeTokenM, final ResponseProcesser<M, T> processer, BusinessCallBack<I> callBack, int method) {        request(context, Configs.SERVER_URL, url, params, typeTokenT, typeTokenM, processer, callBack, method);    }    public <I, T extends I, M> void request(final Context context, final String server, final String url, final HttpRequestParams params, final TypeReference<T> typeTokenT, final TypeReference<M> typeTokenM, final ResponseProcesser<M, T> processer, BusinessCallBack<I> callBack, final int method) {        doTaskASynchronous(callBack, new SyncTask<I>() {            @Override            public BusinessCallBack.Result<I> doTask() {                BusinessCallBack.Result<I> result = doworker(context, server, url, params, typeTokenT, typeTokenM, processer, method);                return result;            }            @Override            public void setInterupted(boolean interupted) {            }            @Override            public boolean isInterupted() {                return false;            }        });    }    /**     * 发起网络请求     */    private <I, T extends I, M> BusinessCallBack.Result<I> doworker(Context context, String server, String actionUrl, HttpRequestParams params, TypeReference<T> typeTokenT, TypeReference<M> typeTokenM, ResponseProcesser<M, T> processer, int method) {        try {            if (params == null) {                params = new HttpRequestParams();            }            String result = serverRequest.requestServerString(server, actionUrl, params.toJson(true), method);//            String result = "{\"musicId\": \"获取成功\",\"musicName\": \"你是我的眼\",\"cpIconPicUrl\": \"http: //www.baidu.com\"}";            LogUtils.v(TAG, "from server| " + actionUrl + ":" + result);            if (TextUtils.isEmpty(result)) {                return null;            }            I tr = null;            if (processer == null || typeTokenM == null) {                if (typeTokenT == null) {                    return null;                }                tr = JSON.parseObject(result, typeTokenT);            } else {                M m = JSON.parseObject(result, typeTokenM);                if (m != null) {                    tr = processer.getResultFromM(m);                }            }            return new BusinessCallBack.Result<>(tr);        }/* catch (HttpRequestError e) {            BusinessCallBack.Result<I> result = new BusinessCallBack.Result<>(null, 0);            result.errorMessage = e.getMessage();            return result;        } */ catch (Exception e) {            BusinessCallBack.Result<I> result = new BusinessCallBack.Result<>(null, 1);            result.errorMessage = "request error";            return result;        }    }    /**     * 异步执行     *     * @param callback     * @param task     */    private <T> void doTaskASynchronous(final BusinessCallBack<T> callback, final SyncTask<T> task) {        ThreadPoolManager.executorService.execute(new Runnable() {            @Override            public void run() {                BusinessCallBack.Result<T> t = task.doTask();                mHandler.post(new CallBackRunnable(callback, t));            }        });    }    /**     * UI线程执行数据返回成功回调     */    private class CallBackRunnable implements Runnable {        BusinessCallBack callback;        BusinessCallBack.Result result;        public CallBackRunnable(BusinessCallBack callback, BusinessCallBack.Result result) {            this.callback = callback;            this.result = result;        }        @Override        public void run() {            if (callback != null) {                callback.onResult(result);            }        }    }    /**     * 异步任务     *     * @param <T>     * @author TLZY067     */    public interface SyncTask<T> {        BusinessCallBack.Result<T> doTask();        /**         * 中断任务         *         * @param interupted         */        void setInterupted(boolean interupted);        /**         * 检查是否中断         *         * @return         */        boolean isInterupted();    }    /**     * 结果处理器,用于封装适配结果,可以为null     *     * @param <M>     * @param <T>     */    public interface ResponseProcesser<M, T> {        T getResultFromM(M m);    }    /**     * 请求返回结果处理     */    class BaseRequestResult {        int status; //http状态码        String message;//成功或失败信息    }}
/** * Created by DangF on 2016/6/8. */public interface IHttpManager {    /**     * 执行网络请求 ,默认post请求     *     * @param context     * @param url     * @param params     * @param typeToken     * @param callBack     * @param <I>     * @param <T>     */    <I, T extends I> void request(Context context, String url, HttpRequestParams params, TypeReference<T> typeToken, BusinessCallBack<I> callBack);    /**     * 执行网络请求     *     * @param context     * @param url     * @param params     * @param typeToken     * @param callBack     * @param method    指定方法 post or get     * @param <I>     * @param <T>     */    <I, T extends I> void request(Context context, String url, HttpRequestParams params, TypeReference<T> typeToken, BusinessCallBack<I> callBack, int method);    /**     * 带转换器请求,用于想对请求结果进行包装处理的情况     *     * @param context     * @param url     * @param params     * @param typeTokenT 转换的成的model     * @param typeTokenM 要转换的model     * @param processer  转换器     * @param callBack     * @param method     * @param <I>     * @param <T>     * @param <M>     */    <I, T extends I, M> void request(final Context context, final String url, final HttpRequestParams params, final TypeReference<T> typeTokenT, final TypeReference<M> typeTokenM, KaraokeHttpManager.ResponseProcesser<M, T> processer, BusinessCallBack<I> callBack, int method);    /**     * 指定server     *     * @param context     * @param server     server 用于不同的模块访问不同的服务器,可以为空     * @param url     * @param params     * @param typeTokenT     * @param typeTokenM     * @param processer     * @param callBack     * @param method     * @param <I>     * @param <T>     * @param <M>     */    <I, T extends I, M> void request(final Context context, final String server, final String url, final HttpRequestParams params, final TypeReference<T> typeTokenT, final TypeReference<M> typeTokenM, final KaraokeHttpManager.ResponseProcesser<M, T> processer, BusinessCallBack<I> callBack, final int method);}
/** * 执行网络请求,解析数据并下发 * Created by DangF on 2016/5/18. */public class KaraokeHttpManager implements IHttpManager {    public static final int METHOD_GET = 0;    public static final int METHOD_POST = 1;    private static final String TAG = "KaraokeHttpManager";    private static KaraokeHttpManager manager = null;    private IHttpRequest serverRequest;    private Handler mHandler = new Handler();    public static KaraokeHttpManager getInstance(Context context) {        if (manager == null) {            manager = new KaraokeHttpManager(context);        }        return manager;    }    private KaraokeHttpManager(Context context) {        serverRequest = new KaraokeServerRequest(context);        Karaoke.init(context, 0, 0);    }    public <I, T extends I> void request(Context context, String url, HttpRequestParams params, TypeReference<T> typeToken, BusinessCallBack<I> callBack) {        request(context, url, params, typeToken, null, null, callBack, METHOD_POST);    }    public <I, T extends I> void request(Context context, String url, HttpRequestParams params, TypeReference<T> typeToken, BusinessCallBack<I> callBack, int method) {        request(context, url, params, typeToken, null, null, callBack, method);    }    public <I, T extends I, M> void request(final Context context, final String url, final HttpRequestParams params, final TypeReference<T> typeTokenT, final TypeReference<M> typeTokenM, final ResponseProcesser<M, T> processer, BusinessCallBack<I> callBack, int method) {        request(context, Configs.SERVER_URL, url, params, typeTokenT, typeTokenM, processer, callBack, method);    }    public <I, T extends I, M> void request(final Context context, final String server, final String url, final HttpRequestParams params, final TypeReference<T> typeTokenT, final TypeReference<M> typeTokenM, final ResponseProcesser<M, T> processer, BusinessCallBack<I> callBack, final int method) {        doTaskASynchronous(callBack, new SyncTask<I>() {            @Override            public BusinessCallBack.Result<I> doTask() {                BusinessCallBack.Result<I> result = doworker(context, server, url, params, typeTokenT, typeTokenM, processer, method);                return result;            }            @Override            public void setInterupted(boolean interupted) {            }            @Override            public boolean isInterupted() {                return false;            }        });    }    /**     * 发起网络请求     */    private <I, T extends I, M> BusinessCallBack.Result<I> doworker(Context context, String server, String actionUrl, HttpRequestParams params, TypeReference<T> typeTokenT, TypeReference<M> typeTokenM, ResponseProcesser<M, T> processer, int method) {        try {            if (params == null) {                params = new HttpRequestParams();            }            String result = serverRequest.requestServerString(server, actionUrl, params.toJson(true), method);//            String result = "{\"musicId\": \"获取成功\",\"musicName\": \"你是我的眼\",\"cpIconPicUrl\": \"http: //www.baidu.com\"}";            LogUtils.v(TAG, "from server| " + actionUrl + ":" + result);            if (TextUtils.isEmpty(result)) {                return null;            }            I tr = null;            if (processer == null || typeTokenM == null) {                if (typeTokenT == null) {                    return null;                }                tr = JSON.parseObject(result, typeTokenT);            } else {                M m = JSON.parseObject(result, typeTokenM);                if (m != null) {                    tr = processer.getResultFromM(m);                }            }            return new BusinessCallBack.Result<>(tr);        }/* catch (HttpRequestError e) {            BusinessCallBack.Result<I> result = new BusinessCallBack.Result<>(null, 0);            result.errorMessage = e.getMessage();            return result;        } */ catch (Exception e) {            BusinessCallBack.Result<I> result = new BusinessCallBack.Result<>(null, 1);            result.errorMessage = "request error";            return result;        }    }    /**     * 异步执行     *     * @param callback     * @param task     */    private <T> void doTaskASynchronous(final BusinessCallBack<T> callback, final SyncTask<T> task) {        ThreadPoolManager.executorService.execute(new Runnable() {            @Override            public void run() {                BusinessCallBack.Result<T> t = task.doTask();                mHandler.post(new CallBackRunnable(callback, t));            }        });    }    /**     * UI线程执行数据返回成功回调     */    private class CallBackRunnable implements Runnable {        BusinessCallBack callback;        BusinessCallBack.Result result;        public CallBackRunnable(BusinessCallBack callback, BusinessCallBack.Result result) {            this.callback = callback;            this.result = result;        }        @Override        public void run() {            if (callback != null) {                callback.onResult(result);            }        }    }    /**     * 异步任务     *     * @param <T>     * @author TLZY067     */    public interface SyncTask<T> {        BusinessCallBack.Result<T> doTask();        /**         * 中断任务         *         * @param interupted         */        void setInterupted(boolean interupted);        /**         * 检查是否中断         *         * @return         */        boolean isInterupted();    }    /**     * 结果处理器,用于封装适配结果,可以为null     *     * @param <M>     * @param <T>     */    public interface ResponseProcesser<M, T> {        T getResultFromM(M m);    }    /**     * 请求返回结果处理     */    class BaseRequestResult {        int status; //http状态码        String message;//成功或失败信息    }}
/** * 定义网络请求实现接口 * Created by DangF on 2016/5/19. */public interface IHttpRequest {    String requestServerString(String server, String url, String params, int method) throws HttpRequestError;    /**     *     * @param url     * @param param     * @param timeOut     * @return     * @throws HttpRequestError     */    String get(String url, String param, int timeOut) throws HttpRequestError;    String post(String url, String param, int timeOut) throws HttpRequestError;}
/** * 使用默认方式实现网络请求 * Created by DangF on 2016/5/19. */public class KaraokeServerRequest implements IHttpRequest {    private final String TAG = getClass().getSimpleName();    Context context;    public KaraokeServerRequest(Context context) {        this.context = context;    }    public String requestServerString(String server, String url, String params, int method) throws HttpRequestError {        String newAurl;//        for (int i = 0; i < 4; i++) {//        if (!url.startsWith("http")) {            newAurl = Configs.getHost(server) + url;        } else {            newAurl = url;        }        if (KaraokeHttpManager.METHOD_POST == method) {            return post(newAurl, params, 30 * 1000);        } else {            return get(newAurl, params, 30 * 1000);        }    }    /**     * 向指定 URL 发送POST方法的请求     *     * @param url   发送请求的 URL     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。     * @return 所代表远程资源的响应结果     */    public String post(String url, String param, int timeOut) throws HttpRequestError {        if (Configs.isDebug) {            LogUtils.d(TAG, "request:  " + url);        }        if (!URLUtil.isHttpUrl(url) && !URLUtil.isHttpsUrl(url)) {            return null;        }        PrintWriter out = null;        BufferedReader in = null;        String result = "";        try {            URL realUrl = new URL(url);            // 打开和URL之间的连接            URLConnection conn;            if (HttpUtils.isWifi(context)) {                conn = realUrl.openConnection();            } else {                String proxyHost = android.net.Proxy.getDefaultHost();                if (proxyHost != null) {                    java.net.Proxy p = new java.net.Proxy(                            java.net.Proxy.Type.HTTP, new InetSocketAddress(                            android.net.Proxy.getDefaultHost(),                            android.net.Proxy.getDefaultPort()));                    conn = realUrl.openConnection(p);                } else {                    conn = realUrl.openConnection();                }            }            // 设置通用的请求属性            conn.setRequestProperty("accept", "*/*");            conn.setConnectTimeout(timeOut);            conn.setRequestProperty("connection", "Keep-Alive");            conn.setRequestProperty("user-agent",                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");            // 发送POST请求必须设置如下两行            conn.setDoOutput(true);            conn.setDoInput(true);            // 获取URLConnection对象对应的输出流            out = new PrintWriter(conn.getOutputStream());            // 发送请求参数            out.print(param);            // flush输出流的缓冲            out.flush();            // 定义BufferedReader输入流来读取URL的响应            in = new BufferedReader(                    new InputStreamReader(conn.getInputStream()));            String line;            while ((line = in.readLine()) != null) {                result += line;            }        } catch (Exception e) {            e.printStackTrace();            throw new HttpRequestError("server error");        }        //使用finally块来关闭输出流、输入流        finally {            try {                if (out != null) {                    out.close();                }                if (in != null) {                    in.close();                }            } catch (IOException ex) {                ex.printStackTrace();                throw new HttpRequestError("server error");            }        }        return result;    }    /**     * 向指定URL发送GET方法的请求     *     * @param url   发送请求的URL     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。     * @return URL 所代表远程资源的响应结果     */    public String get(String url, String param, int timeOut) throws HttpRequestError {        if (!URLUtil.isHttpUrl(url) && !URLUtil.isHttpsUrl(url)) {            return null;        }        String result = "";        BufferedReader in = null;        try {            String urlNameString = param.startsWith("?") ? (url + param) : (url + "?" + param);            LogUtils.d(TAG, "request:  " + urlNameString);            URL realUrl = new URL(urlNameString);            // 打开和URL之间的连接            URLConnection conn;            if (HttpUtils.isWifi(context)) {                conn = realUrl.openConnection();            } else {                String proxyHost = android.net.Proxy.getDefaultHost();                if (proxyHost != null) {                    java.net.Proxy p = new java.net.Proxy(                            java.net.Proxy.Type.HTTP, new InetSocketAddress(                            android.net.Proxy.getDefaultHost(),                            android.net.Proxy.getDefaultPort()));                    conn = realUrl.openConnection(p);                } else {                    conn = realUrl.openConnection();                }            }            // 设置通用的请求属性            conn.setRequestProperty("accept", "*/*");            conn.setRequestProperty("connection", "Keep-Alive");            conn.setConnectTimeout(timeOut);            conn.setRequestProperty("user-agent",                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");            // 建立实际的连接            conn.connect();            // 获取所有响应头字段//            Map<String, List<String>> map = connection.getHeaderFields();//            // 遍历所有的响应头字段//            for (String key : map.keySet()) {//                System.out.println(key + "--->" + map.get(key));//            }            // 定义 BufferedReader输入流来读取URL的响应            in = new BufferedReader(new InputStreamReader(                    conn.getInputStream()));            String line;            while ((line = in.readLine()) != null) {                result += line;            }        } catch (Exception e) {            System.out.println("发送GET请求出现异常!" + e);            e.printStackTrace();            throw new HttpRequestError("server error");        }        // 使用finally块来关闭输入流        finally {            try {                if (in != null) {                    in.close();                }            } catch (Exception e2) {                e2.printStackTrace();                throw new HttpRequestError("server error");            }        }        return result;    }}
/** * Created by DangF on 2016/6/8. */public interface IHttpManager {    /**     * 执行网络请求 ,默认post请求     *     * @param context     * @param url     * @param params     * @param typeToken     * @param callBack     * @param <I>     * @param <T>     */    <I, T extends I> void request(Context context, String url, HttpRequestParams params, TypeReference<T> typeToken, BusinessCallBack<I> callBack);    /**     * 执行网络请求     *     * @param context     * @param url     * @param params     * @param typeToken     * @param callBack     * @param method    指定方法 post or get     * @param <I>     * @param <T>     */    <I, T extends I> void request(Context context, String url, HttpRequestParams params, TypeReference<T> typeToken, BusinessCallBack<I> callBack, int method);    /**     * 带转换器请求,用于想对请求结果进行包装处理的情况     *     * @param context     * @param url     * @param params     * @param typeTokenT 转换的成的model     * @param typeTokenM 要转换的model     * @param processer  转换器     * @param callBack     * @param method     * @param <I>     * @param <T>     * @param <M>     */    <I, T extends I, M> void request(final Context context, final String url, final HttpRequestParams params, final TypeReference<T> typeTokenT, final TypeReference<M> typeTokenM, KaraokeHttpManager.ResponseProcesser<M, T> processer, BusinessCallBack<I> callBack, int method);    /**     * 指定server     *     * @param context     * @param server     server 用于不同的模块访问不同的服务器,可以为空     * @param url     * @param params     * @param typeTokenT     * @param typeTokenM     * @param processer     * @param callBack     * @param method     * @param <I>     * @param <T>     * @param <M>     */    <I, T extends I, M> void request(final Context context, final String server, final String url, final HttpRequestParams params, final TypeReference<T> typeTokenT, final TypeReference<M> typeTokenM, final KaraokeHttpManager.ResponseProcesser<M, T> processer, BusinessCallBack<I> callBack, final int method);}

























0 0
原创粉丝点击