资讯专栏INFORMATION COLUMN

Android网络编程10之Retrofit2后篇[请求参数]

nihao / 712人阅读

摘要:前言在上一篇网络编程九前篇基本使用中我们了解了的最基本的方式访问网络的写法以及请求参数的简单介绍。在这里我们仍旧访问淘宝库。可以看到请求数据是一个字符串,因为淘宝库并不支持此类型所以不会返回我们需要的地理信息数据。

前言

在上一篇[Android网络编程(九)Retrofit2前篇[基本使用]](http://www.jianshu.com/p/c383...中我们了解了Retrofit的最基本的GET方式访问网络的写法以及请求参数的简单介绍。这一篇我们来详细的了解Retrofit的请求参数。

1.GET请求访问网络 动态配置URL地址:@Path

Retrofit提供了很多的请求参数注解,使得请求网路时更加便捷。在这里我们仍旧访问淘宝ip库。其中,@Path用来动态的配置URL地址。请求网络接口代码如下所示。

public interface IpServiceForPath {
    @GET("{path}/getIpInfo.php?ip=59.108.54.37")
    Call getIpMsg(@Path("path") String path);
}

在GET注解中包含了{path},它对应着@Path注解中的"path",而用来替换{path}的正是需要传入的 "String path"的值。接下来请求网络的代码如下所示。

String url = "http://ip.taobao.com/";
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        IpServiceForPath ipService = retrofit.create(IpServiceForPath.class);
        Callcall=ipService.getIpMsg("service");//1
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                String country= response.body().getData().getCountry();
                Toast.makeText(getApplicationContext(),country,Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onFailure(Call call, Throwable t) {
            }
        });

在注释1处,传入"service"来替换 @GET注解中的{path}的值。

动态指定查询条件:@Query与@QueryMap

在上一篇中我们用@Query来动态的替换ip地址为了能更方便的得到该ip所对应的地理信息:

public interface IpServiceForQuery{
    @GET("getIpInfo.php")
    Call getIpMsg(@Query("ip")String ip);
}

但是在网络请求中一般为了更精确的查找到我们所需要的数据,需要传入很多的查询参数,如果用@Query会比较麻烦,这时我们可以采用@QueryMap,将所有的参数集成在一个Map统一传递:

public interface IpServiceForQueryMap {
    @GET("getIpInfo.php")
    Call getIpMsg(@QueryMap Map options);
}
2.POST请求访问网络 传输数据类型为键值对:@Field

传输数据类型为键值对,这是我们最常用的POST请求数据类型,淘宝ip库支持数据类型为键值对的POST请求:

public interface IpServiceForPost {
    @FormUrlEncoded
    @POST("getIpInfo.php")
    Call getIpMsg(@Field("ip") String first);
}

首先用到@FormUrlEncoded注解来标明这是一个表单请求,然后在getIpMsg方法中使用@Field注解来标示所对应的String类型数据的键,从而组成一组键值对进行传递。接下来请求网络的代码如下所示。

 String url = "http://ip.taobao.com/service/";
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        IpServiceForPost ipService = retrofit.create(IpServiceForPost.class);
        Callcall=ipService.getIpMsg("59.108.54.37");
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                String country= response.body().getData().getCountry();
                Toast.makeText(getApplicationContext(),country,Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(Call call, Throwable t) {
            }
        });
传输数据类型Json字符串:@Body

我们也可以用POST方式将Gson字符串作为请求体发送到服务器,请求网络接口代码为:

public interface IpServiceForPostBody {
    @POST("getIpInfo.php")
    Call getIpMsg(@Body Ip ip);
}

用@Body这个注解标识参数对象即可,retrofit会将Ip对象转换为字符串。

public class Ip {
    private String ip;
    public Ip(String ip) {
        this.ip = ip;
    }
}

请求网络的代码基本上都是一致的:

 String url = "http://ip.taobao.com/service/";
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        IpServiceForPostBody ipService = retrofit.create(IpServiceForPostBody.class);
        Callcall=ipService.getIpMsg(new Ip(ip));
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                String country= response.body().getData().getCountry();
                Log.i("wangshu","country"+country);
                Toast.makeText(getApplicationContext(),country,Toast.LENGTH_SHORT).show();
            }

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

            }
        });
    }

运行程序用Fiddler抓包,如下图所示。

可以看到请求数据是一个Json字符串,因为淘宝ip库并不支持此类型所以不会返回我们需要的地理信息数据。

单个文件上传:@Part
public interface UploadFileForPart {
    @Multipart
    @POST("user/photo")
    Call updateUser(@Part MultipartBody.Part photo, @Part("description") RequestBody description);
}

Multipart注解表示允许多个@Part,updateUser方法第一个参数是准备上传的图片文件,使用了MultipartBody.Part类型,另一个参数是RequestBody类型,它用来传递简单的键值对。请求网络代码如下所示。

...
File file = new File(Environment.getExternalStorageDirectory(), "wangshu.png");
RequestBody photoRequestBody = RequestBody.create(MediaType.parse("image/png"), file);
MultipartBody.Part photo = MultipartBody.Part.createFormData("photos", "wangshu.png", photoRequestBody);
UploadFileForPart uploadFile = retrofit.create(UploadFileForPart.class);
Call call = uploadFile.updateUser(photo, RequestBody.create(null, "wangshu"));
...
多个文件上传:@PartMap
@Multipart
@POST("user/photo")
Call updateUser(@PartMap Map photos, @Part("description") RequestBody description);

和单文件上传是类似的,只是使用Map封装了上传的文件,并用@PartMap注解来标示起来。其他的都一样,这里就不赘述了。

3.消息报头Header

Http请求中,为了防止攻击或是过滤掉不安全的访问或是添加特殊加密的访问等等,用来减轻服务器的压力和保证请求的安全,通常都会在消息报头中携带一些特殊的消息头处理。Retrofit也提供了@Header来添加消息报头。添加消息报头有两种方式,一种是静态的,另一种是动态的,先来看静态的方式,如下所示。

interface SomeService {
 @GET("some/endpoint")
 @Headers("Accept-Encoding: application/json")
 Call getCarType();
}

使用@Headers注解添加消息报头,如果想要添加多个消息报头,则可以使用{}包含起来:

interface SomeService {
 @GET("some/endpoint")
 @Headers({
            "Accept-Encoding: application/json",
            "User-Agent: MoonRetrofit"
    })
 Call getCarType();
}

动态的方式添加消息报头如下所示。

interface SomeService {
 @GET("some/endpoint")
 Call getCarType(
 @Header("Location") String location);
}

使用@Header注解,可以通过调用getCarType方法来动态的添加消息报头。

github源码下载

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/70584.html

相关文章

  • Android网络编程9Retrofit2前篇[基本使用]

    摘要:创建增加返回值为的支持这里的加上之前定义的参数形成完整的请求地址用于指定返回的参数数据类型,这里我们支持和类型。完整的代码如下增加返回值为的支持请求参数上文讲了访问网络的基本方法,接下来我们来了解下常用的请求参数。 前言 Retrofit是Square公司开发的一款针对Android网络请求的框架,Retrofit2底层基于OkHttp实现的,而OkHttp现在已经得到Google官方...

    Nosee 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<