请求步骤:
1,定义接口(封装URL地址和数据请求)
2,实例化Retrofit
3,通过Retrofit实例创建接口服务对象
4,接口服务对象调用接口中的方法,获取Call对象
5,Call对象执行请求(异步、同步请求)
目录
1. 定义接口
ApiService.java
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.GET;
/**
* Created on 2019/5/16 10:34
*
* @author Q.PeterGuo
* @version 1.0.0
* @Description
*/
public interface ApiService {
String WEAL_URL = "http://gank.io/api/data/%E7%A6%8F%E5%88%A9/";
@GET("10/1")
Call<ResponseBody> getWealData();
}
2. 在主页面进行网络请求
GetActivity.java
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.example.guolei.retrofit_demo.ok.ApiService;
import java.io.IOException;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
/**
* Created on 2019/5/16 10:33
*
* @author Q.PeterGuo
* @version 1.0.0
* @Description
*/
public class GetActivity extends AppCompatActivity implements View.OnClickListener {
private Button bt_categories;
private TextView tv;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo);
initView();
}
private void initView() {
bt_categories = (Button) findViewById(R.id.bt_categories);
tv = (TextView) findViewById(R.id.tv);
bt_categories.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt_categories:
GetExecute();
break;
}
}
private void GetExecute() {
//1.创建Retrofit对象
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiService.WEAL_URL)
.build();
//2.获取ApiService 接口服务对象
ApiService apiService = retrofit.create(ApiService.class);
//3.获取Call 对象
final Call<ResponseBody> call = apiService.getWealData();
new Thread(new Runnable() { //子线程执行
@Override
public void run() {
//4.Call对象执行请求
try {
Response<ResponseBody> response = call.execute();
final String result = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
tv.setText(result); //默认直接回调主线程
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
网友评论