在Andrroid开发中,网络请求十分常用
而在Android网络请求库中,Retrofit是当下最热的一个网络请求库
依赖
compile 'com.squareup.retrofit2:retrofit:2.0.2' // Retrofit库
compile 'com.squareup.okhttp3:okhttp:3.1.2' // Okhttp库
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
创建一个接口
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
public interface APIInterface {
//接口:https://api.github.com/users/Guolei1130
//注意导包不要导错 看上面包的类型
//第一种方式 在有解析类Bean的情况下 泛型里填解析类Bean
//接口定义:注解方式添加请求方式:get请求内部放拼接的连接和需要传递的参数
//如果不需要传递参数 注解里也要打上"/"或"."
@GET("users/{username}")//username相当于一个名字 会把网址参数传进这个名字里
Call<LoginBean> getLogin(@Path("username")String user);//Path此注解里的参数要和Get注解里的名字参数相同 才能匹配
//第二种方式 没有解析类Bean的情况下 泛型里填ResponseBody
@GET("users/{username}")
Call<ResponseBody> getLoginInfo(@Path("username")String user);
MainActivity
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com")//baseURL
.addConverterFactory(GsonConverterFactory.create()).build();
APIInterface apiInterface = retrofit.create(APIInterface.class);//获取请求接口实例
//第一种有解析类Bean的情况下
/*Call<LoginBean> call = apiInterface.getLogin("Guolei1130");
call.enqueue(new Callback<LoginBean>() {
@Override//主线程
public void onResponse(Call<LoginBean> call, Response<LoginBean> response) {
String login = response.body().login;
Toast.makeText(MainActivity.this, login, Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call<LoginBean> call, Throwable t) {
}*/
//第二种没有解析类 ResponseBody自动解析
Call<ResponseBody> call = apiInterface.getLoginInfo("Guolei1130");
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
Toast.makeText(MainActivity.this, response.body().string(), Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
//同步请求,必须在子线程
// Response<LoginBean> = call.execute();
}
详细请看
http://blog.csdn.net/carson_ho/article/details/73732076