retrofit是一种用于Android网络请求的第三方库,我们可以在 点击打开链接中找到它,相比于OKHttp与Volly等框架或者第三方库来说,retrofit使用起来更为方便,菜鸟如我也能用它调通接口!下面让我来分享一下使用心得:
首先我们要导入这个库:
compile 'com.squareup.retrofit2:retrofit:2.1.0'
在build.gradle的dependencies中假如这段话重新加载工程就可以视同retrofit了。
接下来写一个接口
public interface LoginRequest {
@FormUrlEncoded
@POST("/login_json.aspx")
Call<UserEntity> login(@Field("username") JSONObject jsonObject);
}
在这个接口中@POST是网络请求的方式,有get跟post两种,其中get是一种查阅,而post则可以传送数据到后端,这里我们用post的方式,@FormUrlEncoded则是以Form表单提交数据的注解,它跟下面抽象方法的@Feild注解配套,post括号中的字符串是网址的文件名,在调接口的过程中我们还会设置BaseUrl,而真正的Url就是BaseUrl+“”login_json.aspx“了,在Call中,UserEnity是我创建的一个用户实体类,里面装着用户的信息,这里面定义的变量要与接口文档对应。
package com.rongyan.shangjinlieren.entity;
import com.google.gson.annotations.SerializedName;
import org.json.JSONObject;
/**
* Created by 徐溶延 on 2016/7/8.
*/
public class UserEntity {
@SerializedName("jsonObject")
private JSONObject jsonObject;
@SerializedName("Data")
private User user;
@SerializedName("resultCode")
private int resultCode; //接口返回状态码
@SerializedName("resultMessage")
private String resultMessage; //状态说明
public int getResultCode() {
return resultCode;
}
public void setResultCode(int resultCode) {
this.resultCode = resultCode;
}
public String getResultMessage() {
return resultMessage;
}
public void setResultMessage(String resultMessage) {
this.resultMessage = resultMessage;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public JSONObject getJsonObject() {
return jsonObject;
}
public void setJsonObject(JSONObject jsonObject) {
this.jsonObject = jsonObject;
}
}
在每个变量的上方都要加上注解如
@SerializedName("jsonObject")
改注解是用来gson解析的,所以应该要与接口文档中的参数对应,想要用gson解析要引入依赖
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
上面步骤完成后就可以开始调接口啦,这里完成的是一个登录功能
package com.rongyan.shangjinlieren.activity;
import android.content.Intent;
import android.graphics.Paint;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.rongyan.shangjinlieren.R;
import com.rongyan.shangjinlieren.base.BaseActivity;
import com.rongyan.shangjinlieren.entity.UserEntity;
import com.rongyan.shangjinlieren.network.LoginRequest;
import com.rongyan.shangjinlieren.view.AppActionBar;
import org.json.JSONException;
import org.json.JSONObject;
import butterknife.Bind;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class LoginActivity extends BaseActivity implements Callback<UserEntity> {
@Bind(R.id.findPsw)
TextView findPsw;
@Bind(R.id.inputName)
EditText inputName;
@Bind(R.id.inputPsw)
EditText inputPsw;
@Bind(R.id.login)
Button login;
@Override
protected int layoutResId() {
return R.layout.activity_login;
}
@Override
protected void initActionBar(AppActionBar appActionBar) {
appActionBar.hide();
}
@Override
protected void initViews() {
findPsw.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
}
@OnClick(R.id.register)
public void onRegisterClick() {
startActivity(new Intent(this, RegisterActivity.class));
}
@OnClick(R.id.findPsw)
public void onFindPswClick() {
startActivity(new Intent(this, PswFindActivity.class));
}
@OnClick(R.id.login)
public void onLoginClick() {
String userName = inputName.getText().toString();
String psw = inputPsw.getText().toString();
if (TextUtils.isEmpty(userName)) {
Toast.makeText(this, "请输入用户名", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(psw)) {
Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
return;
}
JSONObject jsonPassword = new JSONObject();
JSONObject jsonUsername = new JSONObject();
try {
jsonUsername.put("username", userName);
jsonUsername.put("password",psw);
} catch (JSONException e) {
e.printStackTrace();
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
LoginRequest request = retrofit.create(LoginRequest.class);
Call<UserEntity> login = request.login(jsonUsername);
login.enqueue(this);
}
@Override
public void onResponse(Call<UserEntity> call, Response<UserEntity> response) {
Toast.makeText(this, response.body().getUser().getUserName() + "is login", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call<UserEntity> call, Throwable t) {
t.printStackTrace();
}
}
其中最重要的部分是这个
其中
addConverterFactory(GsonConverterFactory.create()
这是添加转换工厂,你需要将返回的数据转换城你所需要的
官方给出如下几种转换工厂
Gson: com.squareup.retrofit2:converter-gson
Jackson: com.squareup.retrofit2:converter-jackson
Moshi: com.squareup.retrofit2:converter-moshi
Protobuf: com.squareup.retrofit2:converter-protobuf
Wire: com.squareup.retrofit2:converter-wire
Simple XML: com.squareup.retrofit2:converter-simplexml
Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars
大家可以根据自己的需要依赖相应的第三方库
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://121.43.59.5:8011")
.addConverterFactory(GsonConverterFactory.create())
.build();
LoginRequest request = retrofit.create(LoginRequest.class);
Call<UserEntity> login = request.login(jsonUsername);
login.enqueue(this);
}
@Override
public void onResponse(Call<UserEntity> call, Response<UserEntity> response) {
Toast.makeText(this, response.body().getUser().getUserName() + "is login", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call<UserEntity> call, Throwable t) {
t.printStackTrace();
}
总而言之都是套路大家看懂就好啦
android萌新第一次写博客,写的也不完全毕竟自己也是一个连HttpClient都没去好好看过的人,写的不好的地方也请大神们多多指正!