retrofit框架学习

来源:互联网 发布:汉语拼音注音软件 编辑:程序博客网 时间:2024/05/17 21:51


retrofit 最基本的配置


依赖

dependencies {
 // Retrofit & OkHttp
 compile 'com.squareup.retrofit:retrofit:1.9.0' 
 compile 'com.squareup.okhttp:okhttp:2.2.0
}


Retrofit retrofit = new Retrofit.Builder()        .baseUrl("http://192.168.31.242:8080/springmvc_users/user/")        .addConverterFactory(GsonConverterFactory.create())        .build();IUserBiz userBiz = retrofit.create(IUserBiz.class);Call<List<User>> call = userBiz.getUsers();call.enqueue(new Callback<List<User>>()        {            @Override            public void onResponse(Call<List<User>> call, Response<List<User>> response)            {                Log.e(TAG, "normalGet:" + response.body() + "");            }            @Override            public void onFailure(Call<List<User>> call, Throwable t)            {            }        });


get:
public interface IUserBiz {    @GET("{username}")    Call<User> getUser(@Path("username") String username);}
post:

public interface IUserBiz {    @POST("login")    @FormUrlEncoded    Call<User> login(@Field("username") String username, @Field("password") String password);}
封装:

public class DuoShuoApi {    public static DuoShuoApi getApi(){        return SingleHolder.duoShuoApi;    }    private static class SingleHolder{        public static DuoShuoApi duoShuoApi = new DuoShuoApi();    }    private DuoShuoService service;    //创建retrofit    private DuoShuoApi(){        Retrofit retrofit = new Retrofit.Builder()                .baseUrl("http://api.duoshuo.com")                .addConverterFactory(GsonConverterFactory.create())                .build();        service = retrofit.create(DuoShuoService.class);    }    public DuoShuoService getService(){        return service;    }}



public class DuoShuoActivity extends AppCompatActivity {    private static final String TAG = DuoShuoActivity.class.getSimpleName();    private DuoShuoApi duoShuoApi;    private CommitParam commitParam;//这个是请求的参数    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_duo_shuo);        ButterKnife.bind(this);        duoShuoApi = DuoShuoApi.getApi();        commitParam = new CommitParam();        commitParam.setSecret("key");        commitParam.setAuthor_email("xxx@163.com");        commitParam.setAuthor_name("xxx");        commitParam.setAuthor_url("http://www.devwiki.net");        commitParam.setShort_name("devwiki");        commitParam.setThread_key("2016/03/13/Gradle-Get-SVN-Version-Code/");        commitParam.setMessage("test commit!!!");    }    @OnClick({R.id.create_commit_single, R.id.create_commit_map})    public void onClick(View view) {        switch (view.getId()) {            case R.id.create_commit_single:                createSingle();                break;            case R.id.create_commit_map:                createMap();                break;        }    }    private Callback<CommitResult> callback = new Callback<CommitResult>() {        @Override        public void onResponse(Call<CommitResult> call, Response<CommitResult> response) {            if (response.isSuccessful()){                Log.i(TAG, "success!!!");                Log.i(TAG, "---" + response.body().toString());            } else {                Log.e(TAG, "+++" + response.message());            }        }        @Override        public void onFailure(Call<CommitResult> call, Throwable t) {            Log.e(TAG, "***" + t.getMessage());        }    };    //参数第一种写法    private void createSingle(){        Call<CommitResult> call = duoShuoApi.getService().createCommit(                commitParam.getSecret(),                commitParam.getShort_name(),                commitParam.getAuthor_email(),                commitParam.getAuthor_name(),                commitParam.getThread_key(),                commitParam.getAuthor_url(),                commitParam.getMessage());        call.enqueue(callback);    }    //参数第二种写法    private void createMap(){        Map map = commitParam.createCommitParams();        Call<CommitResult> call = duoShuoApi.getService().createCommit(map);        call.enqueue(callback);    }}

public interface DuoShuoService {    //short_name=official&author_email=jp.chenyang%40gmail.com&author_name=Perchouli    // &thread_id=1152923703638301959&author_url=http%3A%2F%2Fduoshuo.com&message=匿名发表新评论    /**     *     * @param shortName     * @param authorEmail     * @param authorName     * @param threadKey     * @param author_url     * @param message     * @return     */    @FormUrlEncoded    @POST("/posts/create.json")    Call<CommitResult> createCommit(@Field("secret") String secret,                                    @Field("short_name") String shortName,                                    @Field("author_email") String authorEmail,                                    @Field("author_name") String authorName,                                    @Field("thread_key") String threadKey,                                    @Field("author_url") String author_url,                                    @Field("message") String message);    @FormUrlEncoded    @POST("/posts/create.json")    Call<CommitResult> createCommit(@FieldMap Map<String, Object> map);}


参考文章:
http://www.infocool.net/kb/Android/201705/364381.html
http://blog.csdn.net/lmj623565791/article/details/51304204
http://www.cnblogs.com/whoislcj/p/5539239.html