retrofit

简单的:

1.首先

compile ‘com.squareup.retrofit:retrofit:2.0.0-beta2’

compile ‘com.squareup.okhttp:okhttp:2.5.0’
compile ‘com.squareup.okio:okio:1.6.0’
compile ‘com.google.code.gson:gson:2.4’
compile ‘com.squareup.retrofit:converter-gson:2.0.0-beta2’

2.声明接口

public interface GetBaidu{
@GET(“http://www.baidu.com/”)
Call get();
//Call get();//必须是这种形式,这是2.0之后的新形式
//我这里需要返回网页内容,不需要转换成Json数据,所以用了ResponseBody;
//你也可以使用Call get();这样的话,需要添加Gson转换器…后续介绍
}

3.调用接口

//经过测试: baseUrl必须设置,如果 声明接口时@GET使用了完整的url路径,那么baseUrl就会被忽略,否则就是拼接url
Retrofit retrofit = new Retrofit.Builder().baseUrl(“http://www.baidu.com/”).build();//在这里可以添加 Gson转换器等;
GetBaidu getBaidu = retrofit.create(GetBaidu.class);//使用上面声明的接口创建
Call call = getBaidu.get();//获取一个Call,才可以执行请求

//同步请求…
try {
Response bodyResponse = call.execute();
String body = bodyResponse.body().string();//获取返回体的字符串
Log.e(TAG, “”);
} catch (IOException e) {
e.printStackTrace();
}

//异步请求…
call.enqueue(new Callback() {//异步
@Override
public void onResponse(Response response, Retrofit retrofit) {
try {
String body = response.body().string();//获取返回体的字符串
} catch (IOException e) {
e.printStackTrace();
}
Log.e(TAG, “”);
}

  @Overridepublic void onFailure(Throwable t) {Log.e(TAG, "");}

});

2.复杂点的 ,直接解析json的
1.首先
compile ‘com.squareup.retrofit:retrofit:2.0.0-beta2’

compile ‘com.squareup.okhttp:okhttp:2.5.0’
compile ‘com.squareup.okio:okio:1.6.0’
compile ‘com.google.code.gson:gson:2.4’
compile ‘com.squareup.retrofit:converter-gson:2.0.0-beta2’

2.声明接口

public interface GetBaidu{@GET("LifePayment/user/login.json?_mt=5849414f4d492c47554343492c342e342e34&_pla=6365625f616e64725f312e342e365f756e695f636562&_pro=30&_ss=3732307831323830&_uid=383637383232303236393838323934&_ver=1.4.6&mobile=3135383130323938363730&pwd=3936653739323138393635656237326339326135343964643561333330313132&version=1.4.6&macValue=55F5BA03AC37288BF122D1745832EE2D")Call<ResponseCode> get();//Call<T> get();//必须是这种形式,这是2.0之后的新形式
//我这里需要返回网页内容,不需要转换成Json数据,所以用了ResponseBody;
//你也可以使用Call<GsonBean> get();这样的话,需要添加Gson转换器...后续介绍
}

ResponseCode只是一个javabean

public class ResponseCode {public String respCode;public UserModel userModel;public UserModel getUserModel() {return userModel;}public void setUserModel(UserModel userModel) {this.userModel = userModel;}private String respMsg;public String getRespCode() {return respCode;}public void setRespCode(String respCode) {this.respCode = respCode;}public String getRespMsg() {return respMsg;}public void setRespMsg(String respMsg) {this.respMsg = respMsg;}
}

UserModel

/** To change this template, choose Tools | Templates* and open the template in the editor.*/
package cn.xinyu.com.myapplication;import java.util.Date;/*** * @author zhengxiaoguang*/
public class UserModel {private String uid;private String sessionId;private String nickName;private String mobile;private Date createdAt;private Date updatedAt;private Integer status;private String description;private Integer couponTotalAmount;private Integer cardsTotalAmount;private Integer newCouponAmount;private Integer couponObtainCount;private Integer billAmountWithCurMoth;private Integer flag;private String warmMessage;private Integer gradeCount;private Integer attenSinaCount;private Integer attenTencentCount;private Integer shareSinaCount;private Integer shareTencentCount;private Integer shareWeixinCount;private Integer cardAttenSinaCount;private Integer cardAttenTencentCount;private Integer cardShareSinaCount;private Integer cardShareTencentCount;private Integer cardShareWeixinCount;private Integer topPrize;private String qqAppKey;private String qqAppSecret;private String weiXinAppId;private String weiXinAppKey;private String sinaAppKey;private String sinaAppSecret;private long officialWeiboId;private String sharedSecret;private Integer isShareRecommender;private String orderId;private String rewId;// 缴费或者注册成功 获得的抽奖次数private Integer chanceOfShark;public Integer getChanceOfShark() {return chanceOfShark;}public void setChanceOfShark(Integer chanceOfShark) {this.chanceOfShark = chanceOfShark;}public String getOrderId() {return orderId;}public void setOrderId(String orderId) {this.orderId = orderId;}public String getRewId() {return rewId;}public void setRewId(String rewId) {this.rewId = rewId;}public UserModel() {super();}public UserModel(String uid, String sessionId, String mobile,Integer status, Integer couponTotalAmount, Integer newCouponAmount,Integer couponObtainCount) {this.uid = uid;this.sessionId = sessionId;this.mobile = mobile;this.status = status;this.couponTotalAmount = couponTotalAmount;this.newCouponAmount = newCouponAmount;this.couponObtainCount = couponObtainCount;}public UserModel(String uid, String sessionId, String mobile,Integer status, Integer couponTotalAmount, Integer newCouponAmount,Integer couponObtainCount, Integer topPrize) {this.uid = uid;this.sessionId = sessionId;this.mobile = mobile;this.status = status;this.couponTotalAmount = couponTotalAmount;this.newCouponAmount = newCouponAmount;this.couponObtainCount = couponObtainCount;this.topPrize = topPrize;}public Integer getCouponTotalAmount() {return couponTotalAmount;}public void setCouponTotalAmount(Integer couponTotalAmount) {this.couponTotalAmount = couponTotalAmount;}public Date getCreatedAt() {return createdAt;}public void setCreatedAt(Date createdAt) {this.createdAt = createdAt;}public String getDescription() {return description;}public void setDescription(String description) {this.description = description;}public String getMobile() {return mobile;}public void setMobile(String mobile) {this.mobile = mobile;}public String getNickName() {return nickName;}public void setNickName(String nickName) {this.nickName = nickName;}public String getSessionId() {return sessionId;}public void setSessionId(String sessionId) {this.sessionId = sessionId;}public Integer getStatus() {return status;}public void setStatus(Integer status) {this.status = status;}public String getUid() {return uid;}public void setUid(String uid) {this.uid = uid;}public Date getUpdatedAt() {return updatedAt;}public void setUpdatedAt(Date updatedAt) {this.updatedAt = updatedAt;}public Integer getNewCouponAmount() {return newCouponAmount;}public void setNewCouponAmount(Integer newCouponAmount) {this.newCouponAmount = newCouponAmount;}public Integer getCouponObtainCount() {return couponObtainCount;}public void setCouponObtainCount(Integer couponObtainCount) {this.couponObtainCount = couponObtainCount;}public Integer getBillAmountWithCurMoth() {return billAmountWithCurMoth;}public void setBillAmountWithCurMoth(Integer billAmountWithCurMoth) {this.billAmountWithCurMoth = billAmountWithCurMoth;}public String getWarmMessage() {return warmMessage;}public void setWarmMessage(String warmMessage) {this.warmMessage = warmMessage;}public Integer getAttenSinaCount() {return attenSinaCount;}public void setAttenSinaCount(Integer attenSinaCount) {this.attenSinaCount = attenSinaCount;}public Integer getAttenTencentCount() {return attenTencentCount;}public void setAttenTencentCount(Integer attenTencentCount) {this.attenTencentCount = attenTencentCount;}public Integer getGradeCount() {return gradeCount;}public void setGradeCount(Integer gradeCount) {this.gradeCount = gradeCount;}public Integer getShareSinaCount() {return shareSinaCount;}public void setShareSinaCount(Integer shareSinaCount) {this.shareSinaCount = shareSinaCount;}public Integer getShareTencentCount() {return shareTencentCount;}public void setShareTencentCount(Integer shareTencentCount) {this.shareTencentCount = shareTencentCount;}public Integer getShareWeixinCount() {return shareWeixinCount;}public void setShareWeixinCount(Integer shareWeixinCount) {this.shareWeixinCount = shareWeixinCount;}public Integer getTopPrize() {return topPrize;}public void setTopPrize(Integer topPrize) {this.topPrize = topPrize;}public Integer getCardsTotalAmount() {return cardsTotalAmount;}public void setCardsTotalAmount(Integer cardsTotalAmount) {this.cardsTotalAmount = cardsTotalAmount;}public Integer getCardAttenSinaCount() {return cardAttenSinaCount;}public void setCardAttenSinaCount(Integer cardAttenSinaCount) {this.cardAttenSinaCount = cardAttenSinaCount;}public Integer getCardAttenTencentCount() {return cardAttenTencentCount;}public void setCardAttenTencentCount(Integer cardAttenTencentCount) {this.cardAttenTencentCount = cardAttenTencentCount;}public Integer getCardShareSinaCount() {return cardShareSinaCount;}public void setCardShareSinaCount(Integer cardShareSinaCount) {this.cardShareSinaCount = cardShareSinaCount;}public Integer getCardShareTencentCount() {return cardShareTencentCount;}public void setCardShareTencentCount(Integer cardShareTencentCount) {this.cardShareTencentCount = cardShareTencentCount;}public Integer getCardShareWeixinCount() {return cardShareWeixinCount;}public void setCardShareWeixinCount(Integer cardShareWeixinCount) {this.cardShareWeixinCount = cardShareWeixinCount;}public String getQqAppKey() {return qqAppKey;}public void setQqAppKey(String qqAppKey) {this.qqAppKey = qqAppKey;}public String getQqAppSecret() {return qqAppSecret;}public void setQqAppSecret(String qqAppSecret) {this.qqAppSecret = qqAppSecret;}public String getWeiXinAppId() {return weiXinAppId;}public void setWeiXinAppId(String weiXinAppId) {this.weiXinAppId = weiXinAppId;}public String getWeiXinAppKey() {return weiXinAppKey;}public void setWeiXinAppKey(String weiXinAppKey) {this.weiXinAppKey = weiXinAppKey;}public String getSinaAppKey() {return sinaAppKey;}public void setSinaAppKey(String sinaAppKey) {this.sinaAppKey = sinaAppKey;}public String getSinaAppSecret() {return sinaAppSecret;}public void setSinaAppSecret(String sinaAppSecret) {this.sinaAppSecret = sinaAppSecret;}public long getOfficialWeiboId() {return officialWeiboId;}public void setOfficialWeiboId(long officialWeiboId) {this.officialWeiboId = officialWeiboId;}public String getSharedSecret() {return sharedSecret;}public void setSharedSecret(String sharedSecret) {this.sharedSecret = sharedSecret;}public Integer getIsShareRecommender() {return isShareRecommender;}public void setIsShareRecommender(Integer isShareRecommender) {this.isShareRecommender = isShareRecommender;}public Integer getFlag() {return flag;}public void setFlag(Integer flag) {this.flag = flag;}}
  1. 使用
package cn.xinyu.com.myapplication;import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.GestureDetector;
import android.widget.TextView;
import android.widget.Toast;import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.squareup.okhttp.ResponseBody;import java.io.IOException;import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit.Call;
import retrofit.Callback;
import retrofit.GsonConverterFactory;
import retrofit.Response;
import retrofit.Retrofit;public class MainActivity extends AppCompatActivity {@BindView(R.id.tv)TextView textView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);ButterKnife.bind(this);//经过测试: baseUrl必须设置,如果 声明接口时@GET使用了完整的url路径,那么baseUrl就会被忽略,否则就是拼接urlGson gson = new GsonBuilder()
//        2013-09-14 16:45:29.setDateFormat("yyyy-MM-dd HH:mm:ss")
//                .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create();Retrofit retrofit = new Retrofit.Builder().baseUrl("http://testopen.cebbank.com/").addConverterFactory(GsonConverterFactory.create(gson)).build();//在这里可以添加 Gson转换器等;GetBaidu getBaidu = retrofit.create(GetBaidu.class);//使用上面声明的接口创建Call<ResponseCode> call = getBaidu.get();//获取一个Call,才可以执行请求////异步请求....call.enqueue(new Callback<ResponseCode>() {//异步
//            @Override
//            public void onResponse(Response<ResponseBody> response, Retrofit retrofit) {
//                try {
//                    String body = response.body().string();//获取返回体的字符串
//                    Toast.makeText(MainActivity.this,body,Toast.LENGTH_LONG).show();
//                    textView.setText(body);
//
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }@Overridepublic void onResponse(Response<ResponseCode> response, Retrofit retrofit) {ResponseCode responseCode=response.body();textView.setText(responseCode.getUserModel().getQqAppKey());}@Overridepublic void onFailure(Throwable t) {Toast.makeText(MainActivity.this,"failed",Toast.LENGTH_LONG).show();textView.setText(t.toString());}});}
}

如果你的json里面有日期,那么要用个日期转换,不然就会
com.google.gson.JsonSyntaxException: 2013-09-14 16:45:29

retrofit 我花了两天的时间才学会,开始的时候,找资料,他们都讲得太深了,我从来没有成功过。直到自己慢啊,我就喜欢一开始从最简单的做起。

参考:
http://blog.csdn.net/angcyo/article/details/50351247

Retrofit 入门和提高相关推荐

  1. Docker 实战教程之从入门到提高 (五)

    本系列的前四篇文章,我们学习了如何在 Ubuntu 操作系统安装 Docker,并且通过实战练习,了解了 Docker 和宿主机操作系统文件目录互相隔离的实现原理,以及 Docker Volume 的 ...

  2. Docker 实战教程之从入门到提高 (四)

    本系列的前三篇文章,我们学习了如何在 Ubuntu 操作系统安装 Docker,并且通过实战练习,了解了 Docker 和宿主机操作系统文件目录互相隔离的实现原理,以及 Docker Volume 的 ...

  3. Docker 实战教程之从入门到提高(二)

    本系列第一篇文章,Docker 实战教程之从入门到提高 (一),我们已经介绍了如何在 Ubuntu 操作系统中安装 Docker,以及 Proxy 和 Insecure Registry 的配置. 本 ...

  4. 《深入浅出WPF》系列视频(特辑)——MVVM入门与提高(难度300+)

    原文地址为: <深入浅出WPF>系列视频(特辑)--MVVM入门与提高(难度300+) <深入浅出WPF>系列视频(特辑)--MVVM入门与提高(难度300+) 一年多没有推出 ...

  5. 511遇见易语言大漠脚本辅助从入门到提高

    511遇见为了让教程系统化,特意录制易语言大漠插件脚本辅助从入门到提高100课: 教程加入了大漠驱动的配置加载调用,内存找图,圆形.椭圆.矩形.方向.中心渐开线和鼠标特征码的结合扫怪,把游戏窗口嵌入脚 ...

  6. [转载]Shell十三问(入门与提高)

    原文地址:Shell十三问(入门与提高)作者:snowdrop Shell十三问--ChinaUnix论坛精华整理(本文来自Lkydeer对ChinaUnix论坛精华的整理) 原创 ChinaUnix ...

  7. python入门与提高实践 老男孩_跟老男孩学Linux运维:MySQL入门与提高实践

    第10章 MySQL数据库日志知识与企业应用实践 10.1 MySQL常用日志文件知识 10.2 错误日志的介绍与配置 10.3 普通查询日志的介绍与配置 10.4 二进制日志的介绍与配置 10.5  ...

  8. 【MQTT从入门到提高系列 | 01】从0到1快速搭建MQTT测试环境

    这是机器未来的第24篇文章 原文首发地址:https://blog.csdn.net/RobotFutures/article/details/125532208 1. mosquitto概述 Ecl ...

  9. 香饽饽:腾讯强推的Redis天花板笔记,帮助初学者快速入门和提高(核心笔记+面试高频解析)

    前言 在目前的技术选型中,Redis 俨然已经成为了系统高性能缓存方案的事实标准,因此现在 Redis 也成为了后端开发的基本技能树之一. 基于上述情况,今天给大家分享一份我亲笔撰写的阿里内部< ...

最新文章

  1. Python 创建类的成员并访问
  2. XunSearch中常用方法整合
  3. Java设计模式探讨之单例模式
  4. Intel Realsense D435 pipeline对象指什么?
  5. 使用timer控件创建一个简单的报警程序
  6. 【51单片机快速入门指南】4.4.1:python串口接收磁力计数据并进行最小二乘法椭球拟合
  7. scala python_Scala与Python | 哪种编程语言更好
  8. 【易语言】五子棋源码
  9. django-admin.py startproject HelloWorld创建文件提示invalid syntax
  10. 为了实现搜索引擎功能,将正则进行到底!
  11. RIP/EIGRP/OSPF/ISIS使用的端口号/协议号
  12. Revit二次开发——一个简单的插件
  13. Linux下简单命令(一)——返回上一级目录、返回指定目录和返回到名称过长的目录
  14. SP603 OPPO A59 主观体验功耗对比
  15. 简单的neo4j三元组增量插入-通过py2neo实现
  16. 如何以编程方式执行Unwind segue?
  17. 亿级流量实验平台设计与实践
  18. linux 每日学一点《用tar来备份ubuntu系统》
  19. Atlas Antibodies神经胶质瘤标志物的研究意义
  20. vm 虚拟服务器 文件上传,vmware虚拟机怎么和主机之间互传文件?

热门文章

  1. python socket thread_python 使用socket与thread进行实时通信
  2. 廖的python教程_廖雪峰的Python3.x教程.pdf
  3. shell脚本按行读取文件的几种方式
  4. WCF wsHttpBinding之Transport security Mode, clientCredentialType=”Basic”
  5. 用vue优雅地编写UI组件的几条指导原则
  6. Codeforces Round #383 (Div. 1) C(二分图)
  7. php命名空间划重点
  8. 以太坊(Ethereum)开发框架 Truffle 入门(四):编译合约
  9. Linux下vsftpd服务器
  10. Oracle 用数据泵导入导出数据