Retrofit 入门和提高
首先感谢这个哥们,把我从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;
}
}
- 使用
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