Android Studio retrofit

代码展示

倒依赖

implementation 'com.squareup.retrofit2:retrofit:2.2.0'
implementation 'com.squareup.retrofit2:converter-gson:2.2.0'

定义接口
通过注解添加两个方法

public interface GetHttp {
    @GET("/ios/cf/dish_list.php?stage_id=1&limit=20&page=1")
    Call<JavaBean> getBean();

    //拼接网址
    @GET("ios/cf/dish_list.php")
    Call<JavaBean> getBean2(@Query("stage_id") String stage_id, @Query("limit") String limit, @Query("page") String page);
}

两种实现方法,下载字符串拼接与不拼接

package com.example.day11;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

//        getHttp1();
        getHttp2();
    }

    /**
     * 拼接
     */
    private void getHttp2() {
        new Retrofit
                .Builder()
                .baseUrl("http://www.qubaobei.com")
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(GetHttp.class)
                .getBean2("1","20","1")
                .enqueue(new Callback<JavaBean>() {
                    @Override
                    public void onResponse(Call<JavaBean> call, Response<JavaBean> response) {
                        Log.e("###getBean", response.body().toString());
                    }

                    @Override
                    public void onFailure(Call<JavaBean> call, Throwable t) {

                    }
                });
    }

    /**
     * 不拼接
     */
    private void getHttp1() {
        new Retrofit
                .Builder()
                .baseUrl("http://www.qubaobei.com")
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(GetHttp.class)
                .getBean()
                .enqueue(new Callback<JavaBean>() {
                    @Override
                    public void onResponse(Call<JavaBean> call, Response<JavaBean> response) {
                        Log.e("###getBean", response.body().toString());
                    }

                    @Override
                    public void onFailure(Call<JavaBean> call, Throwable t) {

                    }
                });
    }
}

你可能感兴趣的:(Android Studio retrofit)