Android Stuidio——retrofit2的Get請求


只寫Get請求的原因是我就用到了這個,剩下的用到了再補

首先項目結構里添加一下依賴

新建接口:

package ***;

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;

public interface TestService {
    @GET("/api/home/MethodName")
    Call<Reception> API_A(@Query("param1") String param1,@Query("param2") String param2);
    // @GET注解的作用:采用Get方法發送網絡請求,這么寫下來最后框架能自動生成/api/home/MethodName?param1=***&param2=***的地址

// 其中返回類型為Call<*>,*是接收數據的類
    // 如果想直接獲得Responsebody中的內容,可以定義網絡請求返回值為Call<ResponseBody>

    @GET("/api/PDAInterface/{method}/{param1}/{param2}")
    Call<Reception> API_B(@Path("method") String method,@Path("param1") String param1,@Path("param2") String param2);
   // 這里怎么寫都可以,只要和后端那里能對上就行
}

新建接收回應的類,要根據返回的信息結構對應着寫

package ***;

import java.util.ArrayList;
import java.util.List;

public class Reception {
    private int code;
    private String message;
    private String[] data;

    public String[] getData(){
        return data;
    }
}

新建Retrofit封裝的類

public class GetResult extends AppCompatActivity {
    @Override

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

        request();
        //使用Retrofit封裝的方法
    }
    public String[] data;
    public String param1 = null;
    public String param2 = null;
   
    private OkHttpClient.Builder getClient(){
        OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
        httpClientBuilder.connectTimeout(5, TimeUnit.SECONDS);
        //add log record
        if (BuildConfig.DEBUG) {
            //打印網絡請求日志
            LoggingInterceptor httpLoggingInterceptor = new LoggingInterceptor.Builder()
                    .loggable(BuildConfig.DEBUG)
                    .setLevel(Level.BASIC)
                    .log(Platform.INFO)
                    .request("請求")
                    .response("響應")
                    .build();
            httpClientBuilder.addInterceptor(httpLoggingInterceptor);
        }
        return httpClientBuilder;
    }
    public void request()
    {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http:/192.168.***.***:***")//設置網絡請求URL
                .client(getClient().build())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        //創建網絡請求接口的實例
        TestService request = retrofit.create(TestService.class);
        //對發送請求進行封裝
        Call<Reception> call = request.getLoginResult("API_B", param1, param2);
        try {
            Response<Reception> response = call.execute();//同步
            if(response.body() != null) {
                data = response.body().getData();
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM