首先感谢这个哥们,把我从helloworld教会了。

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

retrofit 我花了两天的时间才学会,开始的时候,找资料,他们都讲得太深了,我从来没有成功过。知道上面的那个哥们的博客。 真的,我就喜欢一开始从最开始的做起。

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, “”);

}

  @Override
public 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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this); //经过测试: baseUrl必须设置,如果 声明接口时@GET使用了完整的url路径,那么baseUrl就会被忽略,否则就是拼接url
Gson 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();
// }
// } @Override
public void onResponse(Response<ResponseCode> response, Retrofit retrofit) {
ResponseCode responseCode=response.body();
textView.setText(responseCode.getUserModel().getQqAppKey());
} @Override
public 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 入门和提高的更多相关文章

  1. 包建强的培训课程(16):Android新技术入门和提高

    @import url(/css/cuteeditor.css); Normal 0 10 pt 0 2 false false false EN-US ZH-CN X-NONE $([{£¥·‘“〈 ...

  2. Retrofit 入门学习

    Retrofit 入门学习官方RetrofitAPI 官方的一个例子 public interface GitHubService { @GET("users/{user}/repos&qu ...

  3. webdriver实用指南迁移至gitbbok并改名为selenium webdriver从入门到提高

    背景 几年前我写了一本关于selenium webdriver的小册子,主要讲了一些selenium在进行测试过程中会遇到的场景以及解决方案,陆陆续续在github上收到了100+的star,在这里我 ...

  4. SignalR 2.0 入门与提高

    SignalR 2.0 入门与提高 SignalR 2.0 最近整理了SignalR2.0 部分知识点,原文翻译,由于自己是土鳖,翻译得不好的地方,欢迎指正!仅供各位初学者学习! 第一节. 入门ASP ...

  5. 【转载】【时序约束学习笔记1】Vivado入门与提高--第12讲 时序分析中的基本概念和术语

    时序分析中的基本概念和术语 Basic concept and Terminology of Timing Analysis 原文标题及网址: [时序约束学习笔记1]Vivado入门与提高--第12讲 ...

  6. Android 开发 音视频从入门到提高 任务列表 转载

    <Android 音视频从入门到提高 —— 任务列表> 1. 在 Android 平台绘制一张图片,使用至少 3 种不同的 API,ImageView,SurfaceView,自定义 Vi ...

  7. 关东升的iOS实战系列图书 《iOS实战:入门与提高卷(Swift版)》已经上市

             承蒙广大读者的厚爱我的 <iOS实战:入门与提高卷(Swift版)>京东上市了,欢迎广大读者提出宝贵意见.http://item.jd.com/11766718.html ...

  8. Vuex 2 入门与提高。

    从计数器开始 让我们从一个简单的计数器,开始进入Vuex 的世界: 计数器应用的数据模型很简单:使用一个counter属性来表示计数器的 当前值就够了. 在Vue实例的created钩子 中,应用启动 ...

  9. SignalR 2.0 入门与提高 转载https://www.cnblogs.com/vance/p/SignalR.html

    SignalR 2.0 最近整理了SignalR2.0 部分知识点,原文翻译,由于自己是土鳖,翻译得不好的地方,欢迎指正!仅供各位初学者学习! 第一节. 入门ASP.NET SignalR2.0 1. ...

随机推荐

  1. .Net Core+mySqlSugar的一些稍复杂操作

    介绍一些我尝试的mysqlSugar的数据库操作 修改密码 var status = db.Update<Users>(new { password = user.password }, ...

  2. weex踩坑之旅第一弹 ~ 搭建具有入口文件的weex脚手架

    写在前面的话: weex官方文档不完善,在整个实施过程中遇到过很多坑,中途几次想放弃,总是有些不甘心.攻坚克难,总也是会有一些收获,先将收获进行分享也或是记录,防止忘记.要想用好weex必须对es5/ ...

  3. html便民查询各个工具类实例代码分享(支持pc和移动端)

    1.手机号码查询 <iframe id="api_iframe_51240" name="api_iframe_51240" src="&quo ...

  4. ArcGIS 从FileGDB中导出数据异常 000732

    错误代码:000732 产生原因:文件夹命名时起名为“xxx.gdb”,造成是系统识别异常.

  5. IUserStore------Implements Diagram

  6. 使用CSS设置Chrome打印背景色

    以下内容适用于Chrome浏览器 打印背景色可以通过在打印预览页面勾选背景图形实现 如果需要在用户不勾选的情况下依然能够打印背景色,可以通过css实现,如,table隔行设置背景色: .data-ta ...

  7. 禁止windows自动更新后重新启动

    运行gpedit.msc: 按照下图操作: 参考:http://www.xitongcheng.com/jiaocheng/win7_article_94.html

  8. BZOJ3932(主席树上二分+差分

    按时间作为主席树的版本,每个版本的主席树都是一个权值线段树. 差分消去时间影响 对于当前时间版本的主席树查询前K大即可. 树上二分时结束后切记判定l==r的状态(易错 l==r叶子节点可能存在多个值( ...

  9. Java环境变量搭建(Windows环境)

    变量名:JAVA_HOME 变量值:C:\Program Files (x86)\Java\jdk1.8.0_91        // 要根据自己的实际路径配置 变量名:CLASSPATH 变量值:. ...

  10. 使用pip 提示UnicodeDecodeError: 'ascii' codec can't decode解决方法

    python目录 Python27\Lib\site-packages 建一个文件sitecustomize.py 内容写: import sys sys.setdefaultencoding('gb ...