Retrofit2.0中注解使用套路

之前有讲过Retrofit2.0的简单使用和解析。最近在做Retrofit替换之前使用的AsyncHttpClient,在替换的过程中遇到一些之前忽视的小细节。自己感觉知道这几点在开发中灵活使用Retrofit非常有好处。

说说Retrofit中的注解

@Query,@QueryMap,@Field,@FieldMap,@FormUrlEncoded,@Path,@Url
这七种注解应该是最常用的了。

下边列举各种应用场景。

一、get方式请求静态url地址

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com/")
    .build();
public interface GitHubService {
    //无参数
    @GET("users/stven0king/repos")
    Call<List<Repo>> listRepos();
    //少数参数
    @GET("users/stven0king/repos")
    Call<List<Repo>> listRepos(@Query("time") long time);
    //参数较多
    @GET("users/stven0king/repos")
    Call<List<Repo>> listRepos(@QueryMap Map<String, String> params);
}

@Query和@QueryMap也可以结合在一起使用。

要是对应的url在服务端支持get/post两种类型的请求的话,那么上面的@GET变为@POST也可以执行,只不过post请求时所带的参数也会像get方式一样已?key=value&key1=vaule2…的形式拼接在url的后边。

二、post方式请求静态url地址

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com/")
    .build()
public interface GitHubService {
    //无参数
    @POST("users/stven0king/repos")
    Call<List<Repo>> listRepos();
    //少数参数
    @FormUrlEncoded
    @POST("users/stven0king/repos")
    Call<List<Repo>> listRepos(@Field("time") long time);
    //参数较多
    @FormUrlEncoded
    @POST("users/stven0king/repos")
    Call<List<Repo>> listRepos(@FieldMap Map<String, String> params);
}

@Field和@FieldMap可以结合在一起使用。

另外是不是发现了比起@GET多了一个@FromUrlEncoded的注解。如果去掉@FromUrlEncoded在post请求中使用@Field和@FieldMap,那么程序会抛出java.lang.IllegalArgumentException: @Field parameters can only be used with form encoding. (parameter #1)的错误异常。如果将@FromUrlEncoded添加在@GET上面呢,同样的也会抛出java.lang.IllegalArgumentException:FormUrlEncoded can only be specified on HTTP methods with request body (e.g., @POST).的错误异常。

三、半静态的url地址请求

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com/")
    .build()

public interface GitHubService {
  @GET("users/{user}/repos")
  Call<List<Repo>> listRepos(@Path("user") String user);
}

四、动态的url地址请求

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com/")
    .build()

public interface GitHubService {
  @GET
  Call<List<Repo>> listRepos(@Url String user);
}

五、总结小细节

  • 当@GET或@POST注解的url为全路径时(可能和baseUrl不是一个域),会直接使用注解的url的域。
  • 如果请求为post实现,那么最好传递参数时使用@Field、@FieldMap和@FormUrlEncoded。因为@Query和或QueryMap都是将参数拼接在url后面的,而@Field或@FieldMap传递的参数时放在请求体的。
  • 使用@Path时,path对应的路径不能包含”/”,否则会将其转化为%2F。在遇到想动态的拼接多节url时,还是使用@Url吧。
发布了368 篇原创文章 · 获赞 178 · 访问量 47万+
展开阅读全文

java.lang.IllegalArgumentException求大神帮帮忙!!!

08-24

异常提示:Servlet.service() for servlet [dispatcher] in context with path [/comsed1] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: Bean object must not be null; nested exception is java.lang.IllegalArgumentException: Bean object must not be null] with root cause java.lang.IllegalArgumentException: Bean object must not be null at org.springframework.util.Assert.notNull(Assert.java:112) at org.springframework.beans.BeanWrapperImpl.setWrappedInstance(BeanWrapperImpl.java:213) at org.springframework.beans.BeanWrapperImpl.setWrappedInstance(BeanWrapperImpl.java:202) at org.springframework.beans.BeanWrapperImpl.<init>(BeanWrapperImpl.java:151) at org.springframework.data.util.DirectFieldAccessFallbackBeanWrapper.<init>(DirectFieldAccessFallbackBeanWrapper.java:35) at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.getId(JpaMetamodelEntityInformation.java:117) at org.springframework.data.repository.core.support.AbstractEntityInformation.isNew(AbstractEntityInformation.java:51) at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.isNew(JpaMetamodelEntityInformation.java:196) at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:376) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:483) at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:405) at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:390) at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:344) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodIntercceptor.invoke(CrudMethodMetadataPostProcessor.java:111) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207) at com.sun.proxy.$Proxy136.save(Unknown Source) at iot.service.ProductMasterService.modifyProductMaster(ProductMasterService.java:32) at iot.controller.productMasterController.modifyProductMaster(productMasterController.java:95) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 代码部分: @RequestMapping(value = "modifyProductMasterInit") public String modifyProductMasterInit(@RequestParam("productId") String productId,Model model){ // Iterable<ProductMaster> productMasterList = productMasterDAO.findByProductId(productId); // model.addAttribute("productMasterList", productMasterList); ProductMaster productMaster = this.productMasterService.findByProductId(productId); model.addAttribute("productMaster", productMaster); return "productMaster/Pro_Master_modify"; } @RequestMapping(value = "modifyProductMaster") public String modifyProductMaster(ProductMaster productMaster,@RequestParam("productId") String productId){ ProductMaster productMasterOld = this.productMasterService.findByProductId(productId);//经断点调试productMasterOld为空 try { BeanUtils.copyProperties(productMaster, productMasterOld); } catch (Exception e) { e.printStackTrace(); } this.productMasterService.modifyProductMaster(productMasterOld); return "redirect:/productMaster/loadProductMaster"; } Service方法: @Service public class ProductMasterService { @Autowired(required = false) private ProductMasterDAO productMasterDAO; public void addproductMaster(ProductMaster productMaster) { this.productMasterDAO.save(productMaster); } public ProductMaster findByProductId(String productId) { return this.productMasterDAO.findByProductId(productId); } public void modifyProductMaster(ProductMaster productMaster) { this.productMasterDAO.save(productMaster); } } ProductMasterDAO部分: public interface ProductMasterDAO extends PagingAndSortingRepository<ProductMaster, String>,JpaSpecificationExecutor<ProductMaster>{ @Query("SELECT p FROM ProductMaster p WHERE p.productId = ?1") public ProductMaster findByProductId(String productId); } 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览