retrofit是用来对接口进行get和post请求的
Get请求
测试接口
http://t.weather.sojson.com/api/weather/city/101030100
如果你用postman,直接对接口进行post可以直接得到返回的结果是一样的
public class GetTest {
// 服务请求url
public static final String API_URL = "http://t.weather.sojson.com/api/weather/city/";
public interface ApiService {
@GET("101030100")//这里填入get的参数值
Call<ResponseBody> getRespose();//getResponse()是方法的名称
}
public static void main(String[] args) {
getList();
}
/**
* 获取数据
*/
private static void getList() {
// 创建Retrofit实例
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_URL)//baseUrl里面填入请求的url地址
.build();
// 接口实例化retrofit.create()里面填入对应的接口lass
ApiService service = retrofit.create(ApiService.class);
// 调用具体接口方法
Call<ResponseBody> call = service.getRespose();
//异步执行请求
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
// TODO Auto-generated method stub
try {
System.out.println(response.body().string());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> arg0, Throwable arg1) {
// TODO Auto-generated method stub
}
});
}
}