retrofit初体验

 目标:通过retrofit实现ip地址查询功能

准备工作:

1.api地址:http://ip.taobao.com/instructions.php

参数,返回结果说明如下:

      1>. 请求接口(GET):

         /service/getIpInfo.php?ip=[ip地址字串]

      2>. 响应信息:

       (json格式的)国家 、省(自治区或直辖市)、市(县)、运营商

      3>. 返回数据格式:

        {"code":0,"data":{"ip":"210.75.225.254","country":"\u4e2d\u56fd","area":"\u534e\u5317",
        "region":"\u5317\u4eac\u5e02","city":"\u5317\u4eac\u5e02","county":"","isp":"\u7535\u4fe1",
        "country_id":"86","area_id":"100000","region_id":"110000","city_id":"110000",
        "county_id":"-1","isp_id":"100017"}}
        其中code的值的含义为,0:成功,1:失败。

2.所需要的jar包

     1>retrofit-2.1.0.jar  http://download.csdn.net/detail/wojiaowuming/9613421

     2>okhttp-3.2.0.jar   http://download.csdn.net/detail/wojiaowuming/9613438

     3>okio-1.9.0.jar  http://download.csdn.net/detail/wojiaowuming/9613442

3.所需要的一个返回值解析类(用于设置retrofit返回值类型)

在工程目录下创建一个包,存放以下三个类文件

  1 /*
  2  * Copyright (C) 2015 Square, Inc.
  3  *
  4  * Licensed under the Apache License, Version 2.0 (the "License");
  5  * you may not use this file except in compliance with the License.
  6  * You may obtain a copy of the License at
  7  *
  8  *      http://www.apache.org/licenses/LICENSE-2.0
  9  *
 10  * Unless required by applicable law or agreed to in writing, software
 11  * distributed under the License is distributed on an "AS IS" BASIS,
 12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13  * See the License for the specific language governing permissions and
 14  * limitations under the License.
 15  */
 16 package com.code.pub.model;
 17 
 18 import java.lang.annotation.Annotation;
 19 import java.lang.reflect.Type;
 20 
 21 import okhttp3.RequestBody;
 22 import okhttp3.ResponseBody;
 23 import retrofit2.Converter;
 24 import retrofit2.Retrofit;
 25 
 26 import com.code.pub.model.ScalarResponseBodyConverters.BooleanResponseBodyConverter;
 27 import com.code.pub.model.ScalarResponseBodyConverters.ByteResponseBodyConverter;
 28 import com.code.pub.model.ScalarResponseBodyConverters.CharacterResponseBodyConverter;
 29 import com.code.pub.model.ScalarResponseBodyConverters.DoubleResponseBodyConverter;
 30 import com.code.pub.model.ScalarResponseBodyConverters.FloatResponseBodyConverter;
 31 import com.code.pub.model.ScalarResponseBodyConverters.IntegerResponseBodyConverter;
 32 import com.code.pub.model.ScalarResponseBodyConverters.LongResponseBodyConverter;
 33 import com.code.pub.model.ScalarResponseBodyConverters.ShortResponseBodyConverter;
 34 import com.code.pub.model.ScalarResponseBodyConverters.StringResponseBodyConverter;
 35 
 36 /**
 37  * A {@linkplain Converter.Factory converter} for strings and both primitives and their boxed types
 38  * to {@code text/plain} bodies.
 39  */
 40 public final class ScalarsConverterFactory extends Converter.Factory {
 41   public static ScalarsConverterFactory create() {
 42     return new ScalarsConverterFactory();
 43   }
 44 
 45   private ScalarsConverterFactory() {
 46   }
 47 
 48   @Override public Converter<?, RequestBody> requestBodyConverter(Type type,
 49       Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
 50     if (type == String.class
 51         || type == boolean.class
 52         || type == Boolean.class
 53         || type == byte.class
 54         || type == Byte.class
 55         || type == char.class
 56         || type == Character.class
 57         || type == double.class
 58         || type == Double.class
 59         || type == float.class
 60         || type == Float.class
 61         || type == int.class
 62         || type == Integer.class
 63         || type == long.class
 64         || type == Long.class
 65         || type == short.class
 66         || type == Short.class) {
 67       return ScalarRequestBodyConverter.INSTANCE;
 68     }
 69     return null;
 70   }
 71 
 72   @Override
 73   public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
 74       Retrofit retrofit) {
 75     if (type == String.class) {
 76       return StringResponseBodyConverter.INSTANCE;
 77     }
 78     if (type == Boolean.class || type == boolean.class) {
 79       return BooleanResponseBodyConverter.INSTANCE;
 80     }
 81     if (type == Byte.class || type == byte.class) {
 82       return ByteResponseBodyConverter.INSTANCE;
 83     }
 84     if (type == Character.class || type == char.class) {
 85       return CharacterResponseBodyConverter.INSTANCE;
 86     }
 87     if (type == Double.class || type == double.class) {
 88       return DoubleResponseBodyConverter.INSTANCE;
 89     }
 90     if (type == Float.class || type == float.class) {
 91       return FloatResponseBodyConverter.INSTANCE;
 92     }
 93     if (type == Integer.class || type == int.class) {
 94       return IntegerResponseBodyConverter.INSTANCE;
 95     }
 96     if (type == Long.class || type == long.class) {
 97       return LongResponseBodyConverter.INSTANCE;
 98     }
 99     if (type == Short.class || type == short.class) {
100       return ShortResponseBodyConverter.INSTANCE;
101     }
102     return null;
103   }
104 }
View Code
  1 /*
  2  * Copyright (C) 2016 Square, Inc.
  3  *
  4  * Licensed under the Apache License, Version 2.0 (the "License");
  5  * you may not use this file except in compliance with the License.
  6  * You may obtain a copy of the License at
  7  *
  8  *      http://www.apache.org/licenses/LICENSE-2.0
  9  *
 10  * Unless required by applicable law or agreed to in writing, software
 11  * distributed under the License is distributed on an "AS IS" BASIS,
 12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13  * See the License for the specific language governing permissions and
 14  * limitations under the License.
 15  */
 16 package com.code.pub.model;
 17 
 18 import java.io.IOException;
 19 import okhttp3.ResponseBody;
 20 import retrofit2.Converter;
 21 
 22 final class ScalarResponseBodyConverters {
 23   private ScalarResponseBodyConverters() {
 24   }
 25 
 26   static final class StringResponseBodyConverter implements Converter<ResponseBody, String> {
 27     static final StringResponseBodyConverter INSTANCE = new StringResponseBodyConverter();
 28 
 29     @Override public String convert(ResponseBody value) throws IOException {
 30       return value.string();
 31     }
 32   }
 33 
 34   static final class BooleanResponseBodyConverter implements Converter<ResponseBody, Boolean> {
 35     static final BooleanResponseBodyConverter INSTANCE = new BooleanResponseBodyConverter();
 36 
 37     @Override public Boolean convert(ResponseBody value) throws IOException {
 38       return Boolean.valueOf(value.string());
 39     }
 40   }
 41 
 42   static final class ByteResponseBodyConverter implements Converter<ResponseBody, Byte> {
 43     static final ByteResponseBodyConverter INSTANCE = new ByteResponseBodyConverter();
 44 
 45     @Override public Byte convert(ResponseBody value) throws IOException {
 46       return Byte.valueOf(value.string());
 47     }
 48   }
 49 
 50   static final class CharacterResponseBodyConverter implements Converter<ResponseBody, Character> {
 51     static final CharacterResponseBodyConverter INSTANCE = new CharacterResponseBodyConverter();
 52 
 53     @Override public Character convert(ResponseBody value) throws IOException {
 54       String body = value.string();
 55       if (body.length() != 1) {
 56         throw new IOException(
 57             "Expected body of length 1 for Character conversion but was " + body.length());
 58       }
 59       return body.charAt(0);
 60     }
 61   }
 62 
 63   static final class DoubleResponseBodyConverter implements Converter<ResponseBody, Double> {
 64     static final DoubleResponseBodyConverter INSTANCE = new DoubleResponseBodyConverter();
 65 
 66     @Override public Double convert(ResponseBody value) throws IOException {
 67       return Double.valueOf(value.string());
 68     }
 69   }
 70 
 71   static final class FloatResponseBodyConverter implements Converter<ResponseBody, Float> {
 72     static final FloatResponseBodyConverter INSTANCE = new FloatResponseBodyConverter();
 73 
 74     @Override public Float convert(ResponseBody value) throws IOException {
 75       return Float.valueOf(value.string());
 76     }
 77   }
 78 
 79   static final class IntegerResponseBodyConverter implements Converter<ResponseBody, Integer> {
 80     static final IntegerResponseBodyConverter INSTANCE = new IntegerResponseBodyConverter();
 81 
 82     @Override public Integer convert(ResponseBody value) throws IOException {
 83       return Integer.valueOf(value.string());
 84     }
 85   }
 86 
 87   static final class LongResponseBodyConverter implements Converter<ResponseBody, Long> {
 88     static final LongResponseBodyConverter INSTANCE = new LongResponseBodyConverter();
 89 
 90     @Override public Long convert(ResponseBody value) throws IOException {
 91       return Long.valueOf(value.string());
 92     }
 93   }
 94 
 95   static final class ShortResponseBodyConverter implements Converter<ResponseBody, Short> {
 96     static final ShortResponseBodyConverter INSTANCE = new ShortResponseBodyConverter();
 97 
 98     @Override public Short convert(ResponseBody value) throws IOException {
 99       return Short.valueOf(value.string());
100     }
101   }
102 }
View Code
 1 /*
 2  * Copyright (C) 2015 Square, Inc.
 3  *
 4  * Licensed under the Apache License, Version 2.0 (the "License");
 5  * you may not use this file except in compliance with the License.
 6  * You may obtain a copy of the License at
 7  *
 8  *      http://www.apache.org/licenses/LICENSE-2.0
 9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package com.code.pub.model;
17 
18 import java.io.IOException;
19 import okhttp3.MediaType;
20 import okhttp3.RequestBody;
21 import retrofit2.Converter;
22 
23 final class ScalarRequestBodyConverter<T> implements Converter<T, RequestBody> {
24   static final ScalarRequestBodyConverter<Object> INSTANCE = new ScalarRequestBodyConverter<>();
25   private static final MediaType MEDIA_TYPE = MediaType.parse("text/plain; charset=UTF-8");
26 
27   private ScalarRequestBodyConverter() {
28   }
29 
30   @Override 
31   public RequestBody convert(T value) throws IOException {
32     return RequestBody.create(MEDIA_TYPE, String.valueOf(value));
33   }
34 }
View Code

4.代码编写

   1>定义一个interface接口用于创建请求的函数:

    @GET里面填写的是需要请求的api地址

    getIpInfo函数名为自定义函数(函数名根据自己实际情况自定义)

    @Query("ip")表示需要传递的参数名(这里请求时retrofit工具自动组合后的完整路径是:/service/getIpInfo.php?ip="为后面调用传递的ip")

1     public interface IpInfo{
2         @GET("/service/getIpInfo.php")
3         public Call<String> getIpInfo(@Query("ip") String ip);
4         
5     }

 

   2>网络请求触发代码

      baseUrl为绑定api的根地址

      addConverterFactory设置网络请求后返回的数据类型,ScalarsConverterFactory指的返回String类型(此类为第三步中创建的类)

      

 1         Retrofit  retrofit = new Retrofit.Builder()
 2                                  .baseUrl("http://ip.taobao.com")
 4                                  .addConverterFactory(ScalarsConverterFactory.create())
 5                                  .build();
 6         IpInfo ipInfo = retrofit.create(IpInfo.class);//实例化一个请求接口类
 7         Call<String> callback = ipInfo.getIpInfo("116.228.14.26");//设置传递的参数,并得到一个call类,此时还没有执行请求网络操作
//以下为异步请求网络操作
8 callback.enqueue(new Callback<String>() { 9 10 @Override 11 public void onFailure(Call<String> arg0, Throwable arg1) { 12 // TODO Auto-generated method stub 13 mResponse.setText(arg1.getMessage()); 14 } 15 16 @Override 17 public void onResponse(Call<String> arg0, Response<String> arg1) { 18 // TODO Auto-generated method stub 19 mResponse.setText(arg1.body());//请求网络返回的值 20 } 21 22 });

 

posted @ 2016-08-26 10:35  木木小强  阅读(161)  评论(0)    收藏  举报