标签: retrofit2

Retrofit2 204 No Content 有内容异常

我从服务器获得空 json (“{}”) 作为删除响应,代码为 204。

okhttp3.internal.http.HttpEngine课堂上,有一个令人讨厌的事情被抛出:

  if ((code == 204 || code == 205) && response.body().contentLength() > 0) {
    throw new ProtocolException(
        "HTTP " + code + " had non-zero Content-Length: " + response.body().contentLength());
  }
Run Code Online (Sandbox Code Playgroud)

如果您尝试返回标头中没有内容(服务器端)的内容,内容长度仍然大于 0;

任何非服务器端的想法如何解决这个问题?

android okhttp retrofit2

1
推荐指数
1
解决办法
4394
查看次数

拦截器没有被称为retrofit2

尝试添加拦截器以使用 okhttp3 和 Retrofit2 向请求添加标头。我注意到标头没有添加到请求中,并且我的 system.out.println 调试行从未被调用。不知道为什么,但这是我的代码:

创建服务:

OkHttpClient client = new OkHttpClient();

        client.newBuilder()
                .addInterceptor(new ServiceInterceptor(context))
                .authenticator(new MyAuthenticator(context))
                .build();

        service = (new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build())
                .create(Service.class);
Run Code Online (Sandbox Code Playgroud)

服务拦截器:

public class ServiceInterceptor implements Interceptor {

    private final Context context;

    public ServiceInterceptor(Context context){
        this.context = context;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        System.out.println("Interceptor");

        if(request.header("No-Authentication") == null){
            request = request.newBuilder()
                    .addHeader("User-Agent", "APP NAME")
                    .addHeader("Authorization", "bearer " + PreferenceManager.getDefaultSharedPreferences(context).getString("access_token", ""))
                    .build();
        }

        return chain.proceed(request);
    }
} …
Run Code Online (Sandbox Code Playgroud)

java android okhttp retrofit2

1
推荐指数
1
解决办法
2386
查看次数

改造 2:预期为 BEGIN_ARRAY,但在第 1 行第 2 列路径 $ 处为 BEGIN_OBJECT

我正在使用 Retrofit 2。我在http://ip.jsontest.com/上使用测试 JSON 。这是非常简单的 JSON。为什么我会犯这个错误?

在实际项目中我也有这个错误,但我认为,这是因为我有很大的 JSON。我使用测试 JSON。需要帮忙))

java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

这是 JSON

{“ip”:“54.196.188.78”}

我的界面

public interface UmoriliApi {
    @GET(".")
    Call<List<Test>> getData();
}
Run Code Online (Sandbox Code Playgroud)

我的测试课

public class Test {
    @SerializedName("ip")
    @Expose
    private String ip;

    public String getIp() {
        return ip;
    }
    public void setIp(String ip) {
        this.ip = ip;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的 API 类

public class App extends Application {

    private static UmoriliApi umoriliApi;
    private Retrofit retrofit;

    @Override …
Run Code Online (Sandbox Code Playgroud)

java android json retrofit2

1
推荐指数
1
解决办法
7160
查看次数

Android - 使用 Retrofit 解析没有数组标题的 JSON

在获取 JSON 字符串并在 Android 应用程序中使用它时,我遇到了一些困难。所以,我有这个类 Category2,我在其中定义了类别必须具有的所有字段:

\n\n
public class Category2 {\n\n    @SerializedName("_id")\n    private String _id;\n    @SerializedName("name")\n    private String name;\n    @SerializedName("tasks")\n    private int tasks;\n\n    public Category2(String _id, String name, int tasks) {\n\n        this._id = _id;\n        this.name = name;\n        this.tasks = tasks;\n    }\n\n\n    public String get_id(){\n        return _id;\n    }\n    public void set_id(String _id){\n        this._id = _id;\n    }\n    public String getName(){\n        return name;\n    }\n    public void setName(String name){\n        this.name = name;\n    }\n    public int getTasks() {\n        return tasks;\n    }\n    public void setTasks(int tasks){\n …
Run Code Online (Sandbox Code Playgroud)

android json retrofit2

1
推荐指数
1
解决办法
3021
查看次数

改造除字符之外的路径编码?

我使用改造和我的界面如下

\n\n
 @GET("{link}")\n fun search(@Path(value = "link", encoded = true) link: String?): Call<Any>\n
Run Code Online (Sandbox Code Playgroud)\n\n

我是否需要对除字符“?\”之外的所有链接使用编码。

\n\n

例子:

\n\n

链接-> /api/search?&query=\xd8\xaa\xd8\xb3\xd8\xaa

\n\n

通过改造编码链接 -> api/search%3F&query=%D8%AA%D8%B3%D8%AA

\n\n

我需要这个链接-> api/search?&query=%D8%AA%D8%B3%D8%AA

\n\n

我不需要将字符\'?\'转换为%3F。\ndo 是什么呢?

\n

java android kotlin retrofit retrofit2

1
推荐指数
1
解决办法
1719
查看次数

将通过 Retrofit 获取的在线数据缓存到 Room 中以供离线访问的方法

我正在尝试设计一个可以在线和离线工作的应用程序,我需要设计一种本地缓存系统,我已经尝试了 MVVM 实现,并且能够使用 Room Persistence 库从本地数据库获取数据,但是我我不确定如何从服务器获取数据并使其表现为已存储在数据库中的数据(即本地缓存数据库中),任何帮助将不胜感激

我尝试过实现改造并从中获取数据...但是我的实现会在每次打开数据库时从服务器获取数据,删除以前的数据并用服务器中的数据库填充它,我不认为这是一个可行的实施,因为它需要删除并重新创建数据

class Repository {
private LiveData<List<User>> allUsers;
private static final String TAG = "Repository";
private UserDao userDao;

Repository(Application application) {
    DatabaseClass database = DatabaseClass.getInstance(application);
    userDao = database.databaseDAO();
    allUsers = userDao.getAllUsers();
    Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
    RetrofitApi retrofitApi = retrofit.create(RetrofitApi.class);
    Call<List<User>> userCall = retrofitApi.get();

    userCall.enqueue(new Callback<List<User>>() {
        @Override
        public void onResponse(Call<List<User>> call, Response<List<User>> response) {
            List<User> userList = response.body();
            for (User user: userList
                 ) {
                user = new User(user.title,user.title,user.userId);
                insert(user);

            }
        }

        @Override
        public void …
Run Code Online (Sandbox Code Playgroud)

android caching retrofit2 android-room

1
推荐指数
1
解决办法
3156
查看次数

使用 Retrofit 和 GsonConverterFactory 将 JsonArray 转换为 Kotlin 数据类(预期为 BEGIN_OBJECT,但实际为 BEGIN_ARRAY)

我正在尝试从github( https://github.com/JamesFT/Database-Quotes-JSON/blob/master/quotes.json )加载quotesJson文件。我是改造和所有这些的新手,所以我只是尝试遵循并理解教程(https://android.jlelse.eu/android-networking-in-2019-retrofit-with-kotlins-coroutines-aefe82c4d777)。如果这很愚蠢或者真的很简单,我非常抱歉。我仍在为此苦苦挣扎。如果我能得到一个简短的解释为什么它以其他方式完成,我将不胜感激!

我查看了 Retrofit 的文档,搜索了所有类似的溢出问题。问题是,如果我尝试更改 fun getQuotes(): Deferred<Response<QuoteResponse>> 为, fun getQuotes(): Deferred<ResponseList<Quotes>> 则会出现错误 val quoteResponse = safeApiCall(...

    private val okHttpClient = OkHttpClient().newBuilder()
        .build()

    fun retrofit() : Retrofit = Retrofit.Builder()
        .client(okHttpClient)
        .baseUrl("https://raw.githubusercontent.com/JamesFT/Database-Quotes-JSON/master/")
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(CoroutineCallAdapterFactory())
        .build()


    val quoteApi : QuoteApi = retrofit().create(QuoteApi::class.java)

}
Run Code Online (Sandbox Code Playgroud)

模型

   val quoteAuthor : String,
   val quoteText : String
)

// Data Model for the Response returned from the Api
data class QuoteResponse(
    val results : List<Quote>
)

//A retrofit Network Interface for the Api
interface …
Run Code Online (Sandbox Code Playgroud)

android json gson kotlin retrofit2

1
推荐指数
1
解决办法
4397
查看次数

从改造 2.6.2 更新到改造 2.9.0 后 OkHttpClient.Builder() 中的 java.lang.NoSuchMethodError

早些时候,我在我的项目中使用改造版本 2.6.2来调用 api 服务,一切正常。我正在创建一个自定义Interceptor添加api key到每个请求的标头。

网络拦截器.kt

class NetworkInterceptor() : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {

        var request = chain.request()
            request = request.newBuilder()
                .addHeader("Authorization", "Client-ID ${NetworkConfig.CLIENT_ID}")
                .build()

        return chain.proceed(request)
    }
}
Run Code Online (Sandbox Code Playgroud)

我改装库更新到版本2.9.0和更新后改装版本2.9.0我收到java.lang.NoSuchMethodError该行OkHttpClient.Builder()同时加入InterceptorRetrofit.Builder()

api.kt

interface Api {

    @GET("photos")
    suspend fun getPhotos(
        @Query("page") pageNumber: Int,
        @Query("per_page") pageSize: Int,
        @Query("order_by") orderBy: String
    ) : Response<List<Photo>>

    @GET("photos/random")
    suspend fun getRandomPhoto() : Response<Photo>

    companion object{ …
Run Code Online (Sandbox Code Playgroud)

android kotlin android-studio okhttp retrofit2

1
推荐指数
1
解决办法
516
查看次数

如何使用 Hilt 将 Retrofit 注入到注入到 ViewModel 的 Repository?

我刚刚学习了手动依赖注入,但我正在尝试使用 Hilt 来处理这些依赖注入。

我想将 a 注入ViewModelFragment. 该片段包含在Activity. 现在,我已经添加了注解ApplicationActivityFragment

@HiltAndroidApp
class MovieCatalogueApplication : Application()
Run Code Online (Sandbox Code Playgroud)
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
    ...
}
Run Code Online (Sandbox Code Playgroud)
@AndroidEntryPoint
class HomeFragment : Fragment() {
    private lateinit var binding: FragHomeBinding
    private val viewmodel: HomeViewModel by viewModels()
    ...
Run Code Online (Sandbox Code Playgroud)

可以看出,我的HomeFragment依赖于HomeViewModel. 我已经添加了一个ViewModel 注入,如此处所述。

class HomeViewModel @ViewModelInject constructor(
    private val movieRepository: MovieRepository,
    private val showRepository: ShowRepository,
    @Assisted private val savedStateHandle: SavedStateHandle
) : ViewModel() …
Run Code Online (Sandbox Code Playgroud)

android dependency-injection dagger-2 retrofit2 dagger-hilt

1
推荐指数
1
解决办法
2001
查看次数

在我的 Android 应用程序中激活 ProGuard 时 API 不起作用

启用minifyEnabled=trueAPI后不向服务器发送数据。当我检查服务器时,我发现所有输入都为空。但是,如果我添加-dontobfuscate“proguard-rules.pro”文件,则该应用程序运行良好。我正在使用改造2。我尝试了几乎所有关于改造 2 的 ProGuard 规则。什么都没用!

我的build.gradle文件:

def lifecycleExtensionVersion = '2.2.0'
def butterknifeVersion = '10.1.0'
def supportVersion = '29.0.0'
def retrofitVersion = '2.3.0'
def glideVersion = '4.9.0'
def rxJavaVersion = '2.1.1'
def daggerVersion = '2.14.1'
def mockitoVersion = '2.11.0'

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'

    implementation 'com.google.firebase:firebase-crashlytics:17.2.1'
    implementation 'com.google.firebase:firebase-messaging:20.2.4'
    implementation 'com.google.firebase:firebase-analytics:17.5.0'
    implementation 'com.google.firebase:firebase-auth:19.3.0'

    implementation "com.android.support:design:$supportVersion"
    implementation "android.arch.lifecycle:extensions:$lifecycleExtensionVersion"

    implementation "com.jakewharton:butterknife:$butterknifeVersion"
    implementation 'androidx.work:work-runtime:2.2.0'
    annotationProcessor "com.jakewharton:butterknife-compiler:$butterknifeVersion"

    implementation "com.squareup.retrofit2:retrofit:$retrofitVersion"
    implementation "com.squareup.retrofit2:converter-gson:$retrofitVersion"
    implementation "com.squareup.retrofit2:adapter-rxjava2:$retrofitVersion"

    implementation …
Run Code Online (Sandbox Code Playgroud)

obfuscation android proguard retrofit2

1
推荐指数
1
解决办法
505
查看次数