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

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

问题描述

我正在尝试从以下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

直到现在我都尝试过:

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中任何其他库的情况下使用改型获得作为String的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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