1、创建功能实现接口:
package com.example.webpractice;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Query;
public interface ServiceForRetrofit {
public static final String URL="";
@POST("/videos.json")
@FormUrlEncoded //post时需要加上
Call<ResponseBody> post(@Field("name") String name, @Field("password") String password);
@GET("videos.json")
Call<ResponseBody> get(@Query("name") String name,@Query("password") String password);
}
2、实现方法:
package com.example.webpractice;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import okhttp3.FormBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
public class MainActivity extends AppCompatActivity {
private Retrofit retrofit;
private ServiceForRetrofit serviceForRetrofit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView(){
retrofit=new Retrofit.Builder()
.baseUrl(ServiceForRetrofit.URL) //这里写你的url
.build();
//将接口实现类创建
serviceForRetrofit=retrofit.create(ServiceForRetrofit.class);
}
public void postRetrofit(View v){
//实现方法
Call<ResponseBody> call=serviceForRetrofit.post("Jack","123");
//调用enqueue方法异步返回结果
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
String result=response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this,result , Toast.LENGTH_SHORT).show();
}
});
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
}
public void getRetrofit(View v){
Call<ResponseBody> call=serviceForRetrofit.get("Jack","123");
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
String result=response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this,result , Toast.LENGTH_SHORT).show();
}
});
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
}
}
|