eclipse 从改造2获取字符串响应正文

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35520012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 23:03:54  来源:igfitidea点击:

Get String response body from retrofit2

javaandroideclipseretrofitsquare

提问by Muhammad Umar

I am using retrofit1 old style

我正在使用retrofit1 old style

@GET("/loginUser")
    public Call<Response> login(
            @Query("email") String email,
            @Query("password") String password,
            Callback<Response> callback);

Now i don't want to get "User" class however i want to get a String response.

现在我不想得到“用户”类但是我想得到一个字符串响应。

Previously we were using "Response" However there is no Response in retrofit2,

以前我们使用“响应”但是在改造2中没有响应,

How can i get string response or full body response from the server without using any json parsing?

如何在不使用任何 json 解析的情况下从服务器获取字符串响应或全身响应?

回答by Ankit Aggarwal

Create this class

创建这个类

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

public class ToStringConverterFactory extends Converter.Factory {
    private static final MediaType MEDIA_TYPE = MediaType.parse("text/plain");


    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        if (String.class.equals(type)) {
            return new Converter<ResponseBody, String>() {
                @Override
                public String convert(ResponseBody value) throws IOException {
                    return value.string();
                }
            };
        }
        return null;
    }

    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {

        if (String.class.equals(type)) {
            return new Converter<String, RequestBody>() {
                @Override
                public RequestBody convert(String value) throws IOException {
                    return RequestBody.create(MEDIA_TYPE, value);
                }
            };
        }
        return null;
    }
}

use it with

使用它

Retrofit retrofit = new Retrofit.Builder()
                        .addConverterFactory(new ToStringConverterFactory())
                        .build();

EDIT:You have to define it as

编辑:您必须将其定义为

@GET("/loginUser")
    public Call<String> login(
            @Query("email") String email,
            @Query("password") String password);

There is no callback supported in retrofit2 so you have to remove that. To make it asynchronous, you have to do

Retrofit2 中不支持回调,因此您必须将其删除。要使其异步,您必须执行

Call<String> call = service.login(username, password);
call.enqueue(new Callback<String>() {}

EDITThe above code was for retrofit2 beta 3. For retrofit:2.1.0, you have to create ToStringConverterFactory as -

编辑上面的代码是为retrofit2 beta 3。对于retrofit:2.1.0,你必须将ToStringConverterFactory 创建为-

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

public class ToStringConverterFactory extends Converter.Factory {
    private static final MediaType MEDIA_TYPE = MediaType.parse("text/plain");


    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        if (String.class.equals(type)) {
            return new Converter<ResponseBody, String>() {
                @Override
                public String convert(ResponseBody value) throws IOException {
                    return value.string();
                }
            };
        }
        return null;
    }

    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations,
                                                          Annotation[] methodAnnotations, Retrofit retrofit) {

        if (String.class.equals(type)) {
            return new Converter<String, RequestBody>() {
                @Override
                public RequestBody convert(String value) throws IOException {
                    return RequestBody.create(MEDIA_TYPE, value);
                }
            };
        }
        return null;
    }
}

GOOD TO KNOW:Incase you want to have multiple converters (e.g. a String converter as shown above and also a GSON converter):
Make sure you specify the special-purpose converters first (e.g. String converter) and general converters (like Gson) last!

温馨提示:如果您想拥有多个转换器(例如,如上所示的字符串转换器和 GSON 转换器):
请确保首先指定专用转换器(例如字符串转换器),最后指定通用转换器(如 Gson)!

Converters will be called by the order they have been added, if a converter consumed the response, the follwoing converters will not be called.

转换器将按添加顺序调用,如果转换器消耗了响应,则不会调用后续转换器。

回答by Jose Hidalgo

Retrofit 2.0.0-beta3 adds a converter-scalars module provides a Converter.Factory for converting String, the 8 primitive types, and the 8 boxed primitive types as text/plain bodies. Install this before your normal converter to avoid passing these simple scalars through, for example, a JSON converter.

Retrofit 2.0.0-beta3 添加了一个转换器标量模块,提供了一个 Converter.Factory 用于将 String、8 种基本类型和 8 种装箱基本类型转换为文本/纯体。在您的普通转换器之前安装它,以避免通过例如 JSON 转换器传递这些简单的标量。

回答by Krushik

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(API_BASE_URL)
                .client(getClient())
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

ScalarsConverterFactory above GsonConverterFactory

GsonConverterFactory 上方的 ScalarsConverterFactory