标签: retrofit2

改造2 - URL查询参数

我使用查询参数来设置Google Maps API所需的值.

问题是我不需要&第一个查询参数的符号.

@GET("/maps/api/geocode/json?")
    Call<JsonObject> getLocationInfo(@Query("address") String zipCode,
                                             @Query("sensor") boolean sensor,
                                             @Query("client") String client,
                                             @Query("signature") String signature);
Run Code Online (Sandbox Code Playgroud)

改造产生:

&address=90210&sensor=false&client=gme-client&signature=signkey
Run Code Online (Sandbox Code Playgroud)

当我需要它时,会导致调用失败

address=90210&sensor=false&client=gme-client&signature=signkey
Run Code Online (Sandbox Code Playgroud)

我该如何解决?

java android retrofit retrofit2

52
推荐指数
3
解决办法
7万
查看次数

改造2:从响应机构获取JSON

我想使用改装2从我的api获取字符串json,使用改装1获取此json时我没有问题,但使用retrofit 2 为我返回null.

这就是我的json的样子

{"id":1,"Username":"admin","Level":"Administrator"}
Run Code Online (Sandbox Code Playgroud)

这是我的API

@FormUrlEncoded
@POST("/api/level")
Call<ResponseBody> checkLevel(@Field("id") int id);
Run Code Online (Sandbox Code Playgroud)

这就是我的代码的样子

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Config.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        Api api = retrofit.create(Api.class);
        Call<ResponseBody> call = api.checkLevel(1);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                JsonObject post = new JsonObject().get(response.body().toString()).getAsJsonObject();
                    if (post.get("Level").getAsString().contains("Administrator")) {

                    }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });
Run Code Online (Sandbox Code Playgroud)

我是新手改造2并使用上面的代码,它总是让我的应用程序崩溃因为response.body().toString()返回null.

请指导我如何获取json字符串,以便将其转换为JsonObject.

android json retrofit retrofit2

52
推荐指数
6
解决办法
13万
查看次数

改造"授权","持票人"+令牌

我正在尝试使用Retrofit2,我想添加Token到我的Header喜欢这个:
Authorization: Bearer Tokencode下面不起作用:

public interface APIService {
    @Headers({"Authorization", "Bearer "+ token})
    @GET("api/Profiles/GetProfile?id={id}")
    Call<UserProfile> getUser(@Path("id") String id);
}
Run Code Online (Sandbox Code Playgroud)

我的服务器asp.net webApi 请帮忙我该怎么办?

java android retrofit server retrofit2

49
推荐指数
6
解决办法
5万
查看次数

如何获得Retrofit成功响应状态代码

我无法从像200,201等..响应得到成功响应状态码,我们可以很容易地从得到错误代码RetrofitError的类象error.isNetworkError()error.getResponse().getStatus().获取状态代码有什么解决方法吗?

android retrofit retrofit2

48
推荐指数
3
解决办法
6万
查看次数

使用Retrofit2和Mockito或Robolectric进行Android单元测试

我可以测试一下retrofit2beta4的真实反应吗?我需要Mockito还是Robolectic?

我的项目中没有活动,它将是一个库,我需要测试服务器是否正确响应.现在我有这样的代码而且卡住了......

@Mock
ApiManager apiManager;

@Captor
private ArgumentCaptor<ApiCallback<Void>> cb;

@Before
public void setUp() throws Exception {
    apiManager = ApiManager.getInstance();
    MockitoAnnotations.initMocks(this);
}

@Test
public void test_login() {
    Mockito.verify(apiManager)
           .loginUser(Mockito.eq(login), Mockito.eq(pass), cb.capture());
    // cb.getValue();
    // assertEquals(cb.getValue().isError(), false);
}
Run Code Online (Sandbox Code Playgroud)

我可以做出虚假的回应,但我需要测试真实.它成功了吗?它的身体是否正确?你能帮我代码吗?

android unit-testing mockito robolectric retrofit2

48
推荐指数
2
解决办法
2万
查看次数

如何使用Retrofit从异步回调中返回String或JSONObject?

例如,打电话

api.getUserName(userId, new Callback<String>() {...});
Run Code Online (Sandbox Code Playgroud)

原因:

retrofit.RetrofitError: retrofit.converter.ConversionException:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: 
Expected a string but was BEGIN_OBJECT at line 1 column 2
Run Code Online (Sandbox Code Playgroud)

我想我必须禁用gson解析到POJO但无法弄清楚如何做到这一点.

android retrofit retrofit2

45
推荐指数
4
解决办法
4万
查看次数

如何进行多个请求并等待数据来自retrofit 2.0中的所有请求 - android

当前代码:

Retrofit retrofit = new Retrofit.Builder()
                  .baseUrl(Constant.BASEURL)
                  .addConverterFactory(GsonConverterFactory.create())
                  .build();

APIService service = retrofit.create(APIService.class);

Call<ResponseWrap> call = service.getNewsData();

call.enqueue(new Callback<ResponseWrap>() {

  @Override
  public void onResponse(Call<ResponseWrap> call1, Response<ResponseWrap> response) {
    if (response.isSuccess()) {

        ResponseWrap finalRes = response.body();
        for(int i=0; i<finalRes.getResponse().getResults().size(); ++i){
            String title = finalRes.getResponse().getResults().get(i).getWebTitle();
            News n = new News(titleCategory, title, null);
            newsList.add(n);
        }

        AdapterRecommendation adapter = new AdapterRecommendation(getApplicationContext(), newsList);
        listView.setAdapter(adapter);

    }
    else{
        Toast.makeText(getApplicationContext(), "onResponse  - something wrong" + response.message(), Toast.LENGTH_LONG).show();
    }
  }

  @Override
  public void onFailure(Call<ResponseWrap> call1, Throwable t) {
      Toast.makeText(getApplicationContext(), …
Run Code Online (Sandbox Code Playgroud)

android retrofit2

45
推荐指数
1
解决办法
3万
查看次数

使用Retrofit 2.0和Dagger 2设置动态基本URL

我正在尝试使用Dagger 2使用Retrofit 2.0执行登录操作

这是我如何设置Retrofit依赖

@Provides
@Singleton
Retrofit provideRetrofit(Gson gson, OkHttpClient client) {
    Retrofit retrofit = new Retrofit.Builder()
                            .addConverterFactory(GsonConverterFactory.create(gson)
                            .client(client)
                            .baseUrl(application.getUrl())
                            .build();
    return retrofit;     
}
Run Code Online (Sandbox Code Playgroud)

这是API接口.

interface LoginAPI {
   @GET(relative_path)
   Call<Boolean> logMe();
}
Run Code Online (Sandbox Code Playgroud)

我有三个不同的基本网址用户可以登录.因此,在设置Retrofit依赖项时,我无法设置静态URL.我在Application类上创建了一个setUrl()和getUrl()方法.用户登录后,我在调用API调用之前将url设置为Application.

我像这样使用懒惰注射进行改造

Lazy<Retrofit> retrofit
Run Code Online (Sandbox Code Playgroud)

这样,只有当我可以打电话时,Dagger才会注入依赖关系

retrofit.get()
Run Code Online (Sandbox Code Playgroud)

这部分效果很好.我把url设置为改进依赖.但是,当用户键入错误的基本URL(例如,mywifi.domain.com)时,会出现问题,理解它是错误的并更改它(比如mydata.domain.com).由于Dagger已经为改造创建了依赖关系,因此它不会再做了.所以我必须重新打开应用程序并输入正确的URL.

我阅读了不同帖子,使用Dagger在Retrofit上设置动态网址.在我的情况下,没有什么比这更好的了.我想念什么吗?

android dagger-2 retrofit2

45
推荐指数
5
解决办法
3万
查看次数

NoClassDefFoundError:解析失败:Lokhttp3/internal/Platform

我正在使用Retrofit2图书馆.

我已经尝试更新最新版本:Retrofit2,Gson,Rxjava,OKHttp,HttpLoggingInterceptor ...在build.gradle文件中

build.grade 在申请中

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2',         {
    exclude group: 'com.android.support', module: 'support-annotations'
})

// Default - Android Component
testCompile 'junit:junit:4.12'
compile 'com.android.support:design:24.2.1'
compile 'com.android.support:appcompat-v7:24.2.1'

// Retrofit2 + Gson
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.3.0'
compile 'com.squareup.okhttp3:okhttp:3.4.1'

// RxJva
compile 'io.reactivex:rxandroid:1.2.0'
compile 'io.reactivex:rxjava:1.1.4'
}
Run Code Online (Sandbox Code Playgroud)

但我得到了错误

 > Caused by: java.lang.NoClassDefFoundError: Failed resolution of: Lokhttp3/internal/Platform;
at okhttp3.logging.HttpLoggingInterceptor$Logger$1.log(HttpLoggingInterceptor.java:112)
at okhttp3.logging.HttpLoggingInterceptor.intercept(HttpLoggingInterceptor.java:160)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
at internal.NetworkModule$1.intercept(NetworkModule.java:150)
Run Code Online (Sandbox Code Playgroud)

在下面的代码中

Interceptor provideInterceptor(final …
Run Code Online (Sandbox Code Playgroud)

java android retrofit2 okhttp3

44
推荐指数
1
解决办法
2万
查看次数

41
推荐指数
2
解决办法
2038
查看次数