如何在不使用 GSON 或 android 中的任何其他库的情况下使用改造获得字符串响应 [英] How to get response as String using retrofit without using GSON or any other library in android

查看:27
本文介绍了如何在不使用 GSON 或 android 中的任何其他库的情况下使用改造获得字符串响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从以下 Api 获得响应:

I am trying to get response from the following Api :

https://api.github.com/users/username

但我不知道如何将响应作为 String 获取,以便我可以使用 String 解析并获取 JSONObject.

But I don't know how to get response as String so that I can use the String to parse and get the JSONObject.

使用的改造版本:

改造:2.0.0-beta1

retrofit:2.0.0-beta1

直到现在我都试过这个:

I have tried this until now:

public interface GitHubService {
        @GET("/users/{user}")
        public String listRepos(@Path("user") String user,Callback<String> callback);
    }

检索:

GitHubService service = retrofit.create(GitHubService.class);
        service.listRepos("username", new Callback<String>() {
            @Override
            public void onResponse(Response response) {
                System.out.println(response.toString());
            }

            @Override
            public void onFailure(Throwable t) {

            }
        });

例外:

Caused by: java.lang.IllegalArgumentException: Could not locate call adapter for class java.lang.String. Tried:
    * retrofit.ExecutorCallAdapterFactory
            at retrofit.Utils.resolveCallAdapter(Utils.java:67)
            at retrofit.MethodHandler.createCallAdapter(MethodHandler.java:49)

任何帮助将不胜感激.

推荐答案

** 更新 ** 标量转换器已添加到改造中,允许 String 响应比我的原始答案更简洁下面.

** Update ** A scalars converter has been added to retrofit that allows for a String response with less ceremony than my original answer below.

示例界面——

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

ScalarsConverterFactory 添加到您的改造构建器.注意:如果使用ScalarsConverterFactory和另一个工厂,先添加标量工厂.

Add the ScalarsConverterFactory to your retrofit builder. Note: If using ScalarsConverterFactory and another factory, add the scalars factory first.

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(ScalarsConverterFactory.create())
    // add other factories here, if needed.
    .build();

您还需要在 gradle 文件中包含标量转换器 --

You will also need to include the scalars converter in your gradle file --

implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'

--- 原始答案(仍然有效,只是更多的代码)---

--- Original Answer (still works, just more code) ---

我同意@CommonsWare 的观点,您想拦截请求以自己处理 JSON 似乎有点奇怪.大多数情况下,POJO 拥有您需要的所有数据,因此无需在 JSONObject 领域中乱搞.我怀疑使用自定义 gson TypeAdapter 或改造 Converter 如果您需要操作 JSON.然而,改造提供了更多通过 Gson 进行的 JSON 解析.它还管理 REST 请求中涉及的许多其他繁琐任务.仅仅因为您不想使用其中一项功能,并不意味着您必须将整个功能都扔掉.有时您只想获取原始流,所以这里是如何做到的 -

I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject land. I suspect your specific problem might be better solved using a custom gson TypeAdapter or a retrofit Converter if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -

首先,如果您使用的是 Retrofit 2,您应该开始使用 Call API.使用 okhttp 中的 ResponseBody --

First, if you are using Retrofit 2, you should start using the Call API. Instead of sending an object to convert as the type parameter, use ResponseBody from okhttp --

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

然后你就可以创建并执行你的调用 --

then you can create and execute your call --

GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Response<ResponseBody> response) {
        try {
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(Throwable t) {
        e.printStackTrace();
    }
});

注意 上面的代码对响应对象调用了string(),它将整个响应读入一个字符串.如果您将主体传递给可以摄取流的东西,您可以调用 charStream() 代替.请参阅 ResponseBody 文档.

Note The code above calls string() on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream() instead. See the ResponseBody docs.

这篇关于如何在不使用 GSON 或 android 中的任何其他库的情况下使用改造获得字符串响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆