http://square.github.io/retrofit/
准备
引入
1 2
| compile 'com.squareup.retrofit2:retrofit:2.0.0' compile 'com.squareup.retrofit2:converter-gson:2.+'
|
权限
1
| <uses-permission android:name="android.permission.INTERNET" />
|
协议
1 2
| /api/v1/user/login/{name}/{passwd}
|
Curl
1
| curl -X GET --header 'Accept: application/json' 'http://192.168.1.219/api/v1/user/login/sam/123'
|
开始写代码
写一个API接口
1 2 3 4 5 6 7 8 9 10
| import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path;
public interface LoginService {
@GET("/api/v1/user/login/{name}/{passwd}") Call<Login> login(@Path("name") String name , @Path("passwd") String passwd); }
|
请求响应的Model
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| public class Login {
private int code; private String token;
@Override public String toString() { return "LoginDemo{" + "code=" + code + ", token='" + token + '\'' + '}'; }
public int getCode() { return code; }
public void setCode(int code) { this.code = code; }
public String getToken() { return token; }
public void setToken(String token) { this.token = token; } }
|
分别使用了同步和异步(推荐异步)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.TextView;
import java.io.IOException;
import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.tv);
Retrofit loginRetrofit = new Retrofit.Builder() .baseUrl("http://192.168.1.219") .addConverterFactory(GsonConverterFactory.create()) .build(); LoginService loginService = loginRetrofit.create(LoginService.class); final Call<Login> result = loginService.login("sam", "123");
//同步 new Thread() { @Override public void run() { super.run(); try { //result实例只能用一次,clone可以生成另外一个相同的实例 //这里是同步执行,不能在UI线程执行 Log.e("onCreate: 同步", result.clone().execute().body().toString()); } catch (IOException e) { e.printStackTrace(); } } }.start();
//异步 result.enqueue(new Callback<Login>() { @Override public void onResponse(Call<Login> call, Response<Login> response) { //Do something with response
Log.i("onResponse: 异步", "code = " + response.code()); if (response.body() != null){ Log.i("onResponse: 异步", response.body().toString()); tv.setText(response.body().toString()); } }
@Override public void onFailure(Call<Login> call, Throwable t) { //Do something with failure Log.e("onFailure: 异步", t.toString()); } }); } }
|