Retrofit的基本使用

阅读 163

2022-05-26

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);

3调用

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) {

}
});
}

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 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) {

}
});
}
}


精彩评论(0)

0 0 举报