天天看點

Retrofit的基本使用

0引入Retrofit

implementation 'com.squareup.retrofit2:retrofit:2.9.0'
      

1根據接口文檔建立java接口

public interface HttpbinService {

    @POST("post")
    @FormUrlEncoded//指定用form表單的形式送出
    Call post(@Field("username") String userName, @Field("password") String pwd);

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

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

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

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

            }
        });
    }
}