Retrofit的基本使用

·  阅读 112

这是我参与8月更文挑战的第3天,活动详情查看:8月更文挑战

0引入Retrofit

implementation 'com.squareup.retrofit2:retrofit:2.9.0'
复制代码

1根据接口文档创建java接口


public interface HttpbinService {

    @POST("post")
    @FormUrlEncoded//指定用form表单的形式提交
    Call<ResponseBody> post(@Field("username") String userName, @Field("password") String pwd);

    @GET("get")
    Call<ResponseBody> get(@Query("username") String userName, @Query("password") String pwd);
    }
复制代码

2创建retrofit对象,并生成接口实现类对象

		retrofit = new Retrofit.Builder().baseUrl("https://www.httpbin.org/").build();
        httpbinService = retrofit.create(HttpbinService.class);
复制代码

3调用

public void queryRetrofit(View view) {
        retrofit2.Call<ResponseBody> call = httpbinService.post("lance", "123");
        call.enqueue(new retrofit2.Callback<ResponseBody>() {
            @Override
            public void onResponse(retrofit2.Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
                try {
                    Log.i("wy", "postAsync: " + response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(retrofit2.Call<ResponseBody> call, Throwable t) {

            }
        });
    }
复制代码

2,3总代码

package com.hisense.http;

import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;

import com.hisense.test.R;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Retrofit;

public class RetrofitActivity extends AppCompatActivity {
    private Retrofit retrofit;
    private HttpbinService httpbinService;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_retrofit);
        //创建retrofit对象,并生成接口实现类对象
        retrofit = new Retrofit.Builder().baseUrl("https://www.httpbin.org/").build();
        httpbinService = retrofit.create(HttpbinService.class);
    }

    public void queryRetrofit(View view) {
        retrofit2.Call<ResponseBody> call = httpbinService.post("lance", "123");
        call.enqueue(new retrofit2.Callback<ResponseBody>() {
            @Override
            public void onResponse(retrofit2.Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
                try {
                    Log.i("wy", "postAsync: " + response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(retrofit2.Call<ResponseBody> call, Throwable t) {

            }
        });
    }
}
复制代码
分类:
Android
标签: