美文网首页
retrofit2学习过程中遇到的问题

retrofit2学习过程中遇到的问题

作者: 缥缈丰 | 来源:发表于2018-01-14 23:06 被阅读0次

项目中用到retrofit发送http请求,与其它微服务进行交互,碰到的一个要求,向某个path路径发送post请求.请求参数为json字符串.

请求数据:
{
  "example":[
                   {
                   "data1:":"value1",
                   "data2:":"value2",
                    ......
                   }
            ]
}
1实现的retrofit2 service接口
public interface HttpService {

    @POST("{postPath}")
    Call<ResponseBody> postRequest(@Path("postPath")String postPath, @Body Map<String,List<Map<String,Object>>> requestMap);

}

这里用@Path注解实现动态指定post请求的路径,@Body注解会将map序列化成符合要求的json请求参数

2创建retrofit service实例,发送http请求
    Map<String,Object> map1 = new HashMap();
    map1.put("test1",1);
    map1.put("乱码测试","测试");
    Map<String,Object> map2 = new HashMap();
    map2.put("test2",true);
    List<Map<String,Object>> list = new ArrayList();
    list.add(map1);
    list.add(map2);
    Map<String,List<Map<String,Object>>> map = new HashMap();
    map.put("indexgroups",list);

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://127.0.0.1:8080/")
            .addConverterFactory(JacksonConverterFactory.create())
            .build();
    HttpService httpService = retrofit.create(HttpService.class);
    Call<ResponseBody> indexgroups = httpService.postMap("indexgroups",map );
3. 创建一个简单springboot微服务
  定义一个restcontroller

  @RequestMapping(value = "/indexgroups",method = RequestMethod.POST)
  public String indexgroups(@RequestBody String s) {
  
        return s;
  }
4.碰到的问题

a.通过retrofit发出的请求参数, 微服务接收到的为空,后来百度了好久,发现需要在controller对应的rest方法中加一个@ReuestBody注解,个人猜想可能是由于一般发送post请求的都是通过表单提交的方方式,而这里需要直接发送json字符串,没有@ReuestBody这个注解,springmvc 就无法取到请求的数据

通过加@ReuestBody注解解决

b.之前想着Call中的泛型直接用String类的

@POST("{postPath}")
Call<String> postMap(@Path("postPath")String postPath, @Body Map<String,List<Map<String,Object>>>);

遇到了下面的Exception

Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token
  at [Source: java.io.InputStreamReader@150c158; line: 1, column: 1]
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:216)

泛型使用ResponseBody可以解决,然后通过indexgroups.execute().body().string()获取请求返回的json字符串

以上就是在学习retrofit时碰到的两个问题,记录一下下.

相关文章

网友评论

      本文标题:retrofit2学习过程中遇到的问题

      本文链接:https://www.haomeiwen.com/subject/llbloxtx.html