android retrofit 示例(二)

来源:互联网 发布:linux设置环境变量命令 编辑:程序博客网 时间:2024/06/06 00:41

android retrofit 示例(一)
http://blog.csdn.net/qqduxingzhe/article/details/77351265

gradle 导包

    compile 'com.squareup.retrofit2:retrofit:2.3.0' // 基础(已包含okhttp3)    compile 'com.squareup.retrofit2:converter-gson:2.3.0' // 转换接收到的数据 为 GSON    compile 'com.squareup.retrofit2:converter-scalars:2.3.0' // 转换为 text/plain (字符串类型)    compile 'com.orhanobut:logger:2.1.1' // 日志打印

service 接口参数

@Path 参数替换

userValue 替换指定路径的 user

    // https://github.com/xxxxxx    @GET("{user}")    Call<String> userPage(@Path("user") String userValue);

@Query 参数查询 key value

参数查询
q 指的是 key
qValue 指的是 value

    // https://github.com/search?q=toolbar    @GET("search")    Call<String> query(@Query("q") String qValue);    // https://github.com/search?q=toolbar&type=    @GET("search")    Call<String> query(@Query("q") String qValue, @Query("type") String typeValue);

@QueryMap 参数查询 map

参数较多的情况,可考虑

    @GET("search")    Call<String> query(@QueryMap Map<String,String> map);

@Field 指表单属性

Android访问tomcat的话,
1 修改127.0.0.1为 本机Ipv4地址;2 关闭防火墙

cmd命令 ipconfig 获取ip地址

    // http://127.0.0.1:8080/server1/hello    @FormUrlEncoded    @POST("hello")    Call<String> login(            @Field("name") String name,            @Field("password") String password    );

struts2 服务端

    public String hello() throws Exception {        PrintWriter out = ServletActionContext.getResponse().getWriter();        out.append("getName()="+getName()); // 输出字符串到Android端        out.flush();        out.close();        return null;    }

知识点

1 baseurl 一定要以 / 结尾

不以 / 结尾,则抛出异常

===

public Builder baseUrl(String baseUrl) {

      HttpUrl httpUrl = HttpUrl.parse(baseUrl);      if (httpUrl == null) {        throw new IllegalArgumentException("Illegal URL: " + baseUrl);      }      return baseUrl(httpUrl);

public Builder baseUrl(HttpUrl baseUrl) {

      List<String> pathSegments = baseUrl.pathSegments();      if (!"".equals(pathSegments.get(pathSegments.size() - 1))) {        throw new IllegalArgumentException("baseUrl must end in /: " + baseUrl); // 异常(baseurl 必须以 / 结尾)      }

2 service 中 请求方法(@GET、@POST)等 value 填写绝对路径或相对路径

(绝对路径:https://github.com/)
若value 为绝对路径,则 baseurl 无效

3 移除 call 请求

call.cancel();

end

原创粉丝点击