Retrofit它是Square公司开发的网络框架,所以我们在导入它的包的时候都可以看到这个公司的名字,目前的版本是2。
本章主要是以重新创建一个新项目,添加retrofit2的支持,使用POST请求,接收的结果为字符串或直接转成实体类对象。
一、新建一个新的项目;
二、添加网络权限;
三、添加retrofit2库其相关转换库;
四、增加retrofit2基础类(服务器地址配置、延迟时间、接收的数据转换等);
五、增加接口统一管理类,及相关实体类;
六、调用接口。
以下是对应代码
一、新建一个新的项目
二、添加网络权限
三、添加retrofit2库其相关转换库
//Retrofit2处理网络事务的依赖库
compile 'com.squareup.retrofit2:retrofit:2.1.0'
//gson解析可以返回已解析好,为实体类数组的数据
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
//scalars解析可以反回String字符串
compile 'com.squareup.retrofit2:converter-scalars:2.1.0'
四、增加retrofit2基础类(服务器地址配置、延迟时间、接收的数据转换等)
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
/**
* 项目名称:wms
* 类名称:RetrofitBase
* 类描述:Retrofit基础类,接口相关及列表刷新加载统一处理
* 创建人: wjl
* 创建时间: 2016/11/24 11:49
*/
public class RetrofitBase {
/**
* Retrofit初始化( compile 'com.squareup.retrofit2:converter-gson:2.1.0' )
*/
public static RetrofitService retrofit() {
return new Retrofit.Builder()
.baseUrl("http://192.168.1.66:8082/wms/")//服务器链接
.addConverterFactory(GsonConverterFactory.create()) // Gson解析(实体类)
.build().create(RetrofitService.class);
}
/**
* Retrofit初始化
* 可以返回String( compile 'com.squareup.retrofit2:converter-scalars:2.1.0' )
*/
public static RetrofitService retrofitStr() {
long DEFAULT_TIMEOUT = 1000000;//延迟时间设置
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
.writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
.readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
.build();
return new Retrofit.Builder()
.baseUrl("http://192.168.1.66:8082/wms/")//服务器链接
// ScalarsConverterFactory解析(字符串)
.addConverterFactory(ScalarsConverterFactory.create())
.client(client)//设置延迟时间
.build().create(RetrofitService.class);
}
}
五、增加接口统一管理类,及相关实体类
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
/**
* 项目名称:sanhemu
* 类名称:RetrofitService
* 类描述:接口统一管理
* 创建人: wjl
* 创建时间: 2017/05/17 10:51
*/
public interface RetrofitService {
@FormUrlEncoded
@POST("xxx")//xxx具体接口具体命名
Call
xxx(@Field("jsonStr") String jsonStr);
@FormUrlEncoded
@POST("xxx")//xxx具体接口具体命名
Call
xxx(@Field("jsonStr") String jsonStr);
@FormUrlEncoded
@POST("xxx")//xxx具体接口具体命名
Call
xxx(@Field("jsonStr") String jsonStr);
}import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* 项目名称:sanhemu
* 类名称:InterfaceEntity
* 类描述:返回数据为单个数据
* 创建人: wjl
* 创建时间: 2017/5/17 9:28
*/
public class InterfaceEntity implements Serializable {
private static final long serialVersionUID = 1L;
private String returnCode = "";
private Map returnValue = new HashMap();
private String msg = "";
public String getReturnCode() {
return returnCode;
}
public void setReturnCode(String returnCode) {
this.returnCode = returnCode;
}
public Map getReturnValue() {
return returnValue;
}
public void setReturnValue(Map returnValue) {
this.returnValue = returnValue;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public InterfaceEntity(String returnCode, Map returnValue, String msg) {
this.returnCode = returnCode;
this.returnValue = returnValue;
this.msg = msg;
}
@Override
public String toString() {
return "InterfaceEntity{" +
"returnCode='" + returnCode + '\'' +
", returnValue=" + returnValue +
", msg='" + msg + '\'' +
'}';
}
}import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* 项目名称:sanhemu
* 类名称:InterfaceListEntity
* 类描述:返回数据为数组
* 创建人: wjl
* 创建时间: 2017/5/17 9:28
*/
public class InterfaceListEntity implements Serializable {
private static final long serialVersionUID = 1L;
private String returnCode = "";
private List
六、调用接口
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
import java.util.Map;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static wei.shm.retrofitdemo.RetrofitBase.retrofit;
import static wei.shm.retrofitdemo.RetrofitBase.retrofitStr;
public class MainActivity extends AppCompatActivity {
private TextView textview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview = (TextView) findViewById(R.id.textview);
JSONObject mJson = new JSONObject();
try {
mJson.put("xxx", "xxx");//调用参数
} catch (JSONException e) {
e.printStackTrace();
}
//获取字符串的返回数据
retrofitStr().xxx(mJson.toString()).enqueue(new Callback
() {
@Override
public void onResponse(Call
call, Response
response) {
try {
JSONObject mObject = new JSONObject(response.body());
String returnCode = mObject.get("returnCode").toString();
if("1".equals(returnCode)){//接口调用成功
textview.setText(mObject.get("returnValue").toString());
}else{//接口调用失败
Toast.makeText(MainActivity.this,mObject.get("returnValue").toString(),Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call
call, Throwable t) {
Log.i("shm",call.toString() + "|||" + t.toString());
}
});
//获取实体类对象的返回数据
retrofit().xxx(mJson.toString()).enqueue(new Callback
() { @Override public void onResponse(Call
call, Response
response) { InterfaceEntity mInterfaceEntity = response.body(); if("1".equals(mInterfaceEntity.getReturnCode())){//接口调用成功 textview.setText(mInterfaceEntity.getReturnValue().toString()); }else{//接口调用失败 Toast.makeText( MainActivity.this, mInterfaceEntity.getReturnValue().toString(), Toast.LENGTH_LONG).show(); } } @Override public void onFailure(Call
call, Throwable t) { Log.i("shm",call.toString() + "|||" + t.toString()); } }); JSONObject mJsons = new JSONObject(); try { mJsons.put("xxx", "xxx");//调用参数 } catch (JSONException e) { e.printStackTrace(); } //获取实体类对象的返回数据数组 retrofit().xxx(mJson.toString()).enqueue(new Callback
() { @Override public void onResponse(Call
call, Response
response) { InterfaceListEntity mInterfaceListEntity = response.body(); Log.i("shm",mInterfaceListEntity.toString()); if("1".equals(mInterfaceListEntity.getReturnCode())){//接口调用成功 List
mReturnValue = mInterfaceListEntity.getReturnValue(); List mRatch = (List) mReturnValue.get(0).get("xxx"); textview.setText("!"+mRatch.get(0).get("xxx")); }else{//接口调用失败 Toast.makeText( MainActivity.this, mInterfaceListEntity.getReturnValue().toString(), Toast.LENGTH_LONG).show(); } } @Override public void onFailure(Call
call, Throwable t) { Log.i("shm",call.toString() + "|||" + t.toString()); } }); } }