当前位置: 首页 > 工具软件 > Post2Blog > 使用案例 >

retrofit2 post url拼接设置问题

柴飞扬
2023-12-01

我们用retrofit2.0 请求时最好把log带上,可以很详细的告诉我们出错在哪里,AS里导包

compile 'com.squareup.okhttp3:logging-interceptor:3.3.0'

在请求里添加日志管理
 String BASE_URL = "http://www.xxx.com/test/rest/user/";
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(logging).build();

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
        .client(client)
        .build();

@POST设置  2.0后这样会出问题
@POST("/{user}/setDeviceName")
Observable<String> testPost( @Path("user") String user);

测试
api.testPost("test1")
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(System.out::println, throwable -> {
            System.out.println(throwable.getMessage());
        });
运行log
D/OkHttp: --> POST http://www.xxx.com/test1/setDeviceName http/1.1 

post的url路径怎么变成这样了,按照理解应该是 

http://www.xxx.com/test/rest/user/test1/setDeviceName
@POST里面可以写入一个完整的url,或者用来拼接,看了其他人的博客资料,2.0后base_url要以"/"结尾,@POST @POST等请求不要以“/”开头,然后我把@POST 修改下
@POST("{user}/setDeviceName")
Observable<String> testPost( @Path("user") String user);

结果url拼接了
D/OkHttp: --> POST http://www.xxx.com/beehive/rest/user/test1/setDeviceName http/1.1



 类似资料: