38. 网络加载框架Retrofit

38. 网络加载框架Retrofit
38.1 Retrofit简介
Retrofit 是一个 RESTful 的 HTTP 网络请求框架的封装。
原因:网络请求的工作本质上是 OkHttp 完成,而 Retrofit 仅负责 网络请求接口的封装

官方地址:

https://github.com/square/retrofit

最新版本

在这里插入图片描述

引入依赖

在这里插入图片描述

同步

38.2 Retrofit基本使用

服务器依然使用httpbin

在这里插入图片描述

域名:https://www.httpbin.org/

接口:post

参数:username, password

接口:get

参数:username,password

→ 根据接口创建Java接口

package com.dingjiaxiong.myretrofit;

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 HttpBinService { 
    
    @POST("post")
    @FormUrlEncoded
    Call<ResponseBody> post(@Field("username") String userName ,@Field("password") String pwd);

    @GET("get")
    Call<ResponseBody> get(@Query("username") String userName ,@Query("password") String pwd);
    
}


第二步:创建Retrofit对象,并生成接口实现类对象

package com.dingjiaxiong.myretrofit;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class MainActivity extends AppCompatActivity {


    private Retrofit retrofit;
    private HttpBinService httpBinService;

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

        retrofit = new Retrofit.Builder().baseUrl("https://www.httpbin.org/").build();

        httpBinService =retrofit.create(HttpBinService.class);

    }

    public void postAsync(View view) {

        Call<ResponseBody> call = httpBinService.post("dingjiaxiong", "123");
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    Log.e("dingjiaxiong", "onResponse: " + response.body().string() );
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

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

            }
        });
    }
}


布局文件

就一个按钮

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical"
    >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="post异步请求"
        android:onClick="postAsync"
        />

</LinearLayout>


一定记得在清单文件中加权限,不然会直接退出

运行

在这里插入图片描述

OK

38.3 Retrofit中的注解

分类:

方法注解:@GET , @POST , @PUT , @DELETE , @PATH , @HEAD , @OPTIONS , @HTTP
标记注解:@FormUrlEncoded , @Multipart , @Streaming
参数注解:@Query , @QueryMap , @Body , @FieldMap , @Part , @PartMap
其他注解:@Path , @ Header , @Headers , @Url

在这里插入图片描述

@HTPP 注解可以自定义请求的方式。

在这里插入图片描述

使用上就是调方法、传参。

参数注解@Body演示测试

接口:

@POST("post")
Call<ResponseBody> postBody(@Body RequestBody requestBody);


package com.dingjiaxiong.myretrofit;

import org.junit.Test;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.ResponseBody;
import retrofit2.Response;
import retrofit2.Retrofit;

public class AnnitationUnitTest {

    Retrofit retrofit = new Retrofit.Builder().baseUrl("https://www.httpbin.org/").build();
    HttpBinService httpBinService = retrofit.create(HttpBinService.class);

    @Test
    public void bodyTest() throws IOException {
        FormBody formBody = new FormBody.Builder()
                .add("a", "1")
                .add("b", "2").build();
        Response<ResponseBody> response = httpBinService.postBody(formBody).execute();
        System.out.println(response.body().string());
    }
}

在这里插入图片描述

@Path注解演示

@POST("{id}")
Call<ResponseBody> postPath(@Path("id") String path);

 


@Test
public void pathTest() throws IOException {
    Response<ResponseBody> response = httpBinService.postPath("post").execute();
    System.out.println(response.body().string());
}

在这里插入图片描述

实际上就是完成了一个post 请求。

加个参数。

在这里插入图片描述

在这里插入图片描述

运行

在这里插入图片描述

ok。

@Header注解用于设置请求头

演示

再加一个参数

在这里插入图片描述

调用时

在这里插入图片描述

在这里插入图片描述

OK

@Headers注解

在这里插入图片描述

@Test
public void headersTest() throws IOException {
    Response<ResponseBody> response = httpBinService.postWithHeaders().execute();
    System.out.println(response.body().string());
}

运行

在这里插入图片描述

@Url注解

在这里插入图片描述

测试方法

@Test
public void UrlTest() throws IOException {
    Response<ResponseBody> response = httpBinService.postUrl("https://www.httpbin.org/post").execute();
    System.out.println(response.body().string());
}

运行

报错了,加上@POST

在这里插入图片描述

再运行

在这里插入图片描述

请求成功。

作用:指定一个地址,作为这次请求的一个完整的请求地址。

posted @ 2022-09-19 08:46  随遇而安==  阅读(25)  评论(0编辑  收藏  举报