retrofit2发送接收请求

本文介绍了如何在Java项目中使用Retrofit2库进行网络请求。首先在pom.xml中添加Retrofit2和Gson的依赖,接着定义网络请求接口,通过Retrofit.Builder创建Retrofit实例,并设置基础URL和转换器。然后,通过Retrofit实例获取网络请求接口的Call对象,执行请求并处理返回数据,包括检查响应状态和解析JSON。
摘要由CSDN通过智能技术生成

retrofit2发送接收请求

pom中添加依赖

        <!--retrofit2-->
        <dependency>
            <groupId>com.squareup.retrofit2</groupId>
            <artifactId>retrofit</artifactId>
            <version>2.9.0</version>
        </dependency>
        <dependency>
            <groupId>com.squareup.retrofit2</groupId>
            <artifactId>converter-gson</artifactId>
            <version>2.9.0</version>
        </dependency>
    </dependencies>
  1. 创建 用于描述网络请求的接口

    public interface MetaManApi {
         @GET("property/ent/{categoryId}")//网络请求接口的后半部分
        Call<QueryResponse> getAttribute(@Path("categoryId") String categoryId);
    }
    
  2. 创建 Retrofit 实例

       Retrofit retrofit=new Retrofit.Builder()
                    .baseUrl(sysConfig.getMetaservice_ip()+"/meta/")//网络请求URL
                    .addConverterFactory(GsonConverterFactory.create//添加Gson支持,然后Retrofit就会使用Gson将响应体(api接口的Take)转换我们想要的类型
                    .build();
       
    
  3. 创建 网络请求接口实例

      Call<QueryResponse> call= retrofit.create(MetaManApi.class).getAttribute(categoryId);
    
  4. 处理返回数据

QueryResponse responseBody = null;
        try {
            responseBody = call.execute().body();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(responseBody!=null&&responseBody.isSuccess()){
            String json = responseBody.getJson();
            if(StringUtils.isEmpty(json)){
                return Collections.emptyList();
            }else{
                //对json进行进一步处理
                return getListData("properties", json, VoProType.class);
            }
        }else{
            return Collections.emptyList();
        }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值