如何从 Retrofit2 获取字符串响应? [英] How to get string response from Retrofit2?

查看:65
本文介绍了如何从 Retrofit2 获取字符串响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做 android,正在寻找一种方法来执行超级基本的 http GET/POST 请求.我不断收到错误消息:

I am doing android, looking for a way to do a super basic http GET/POST request. I keep getting an error:

java.lang.IllegalArgumentException: Unable to create converter for class java.lang.String

网络服务:

public interface WebService {
    @GET("/projects")
    Call<String> jquery();
}

然后在我的 Java 中:

then in my java:

    Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://jquery.org")
       // .addConverterFactory(GsonConverterFactory.create())
        .build();

    WebService service = retrofit.create(WebService.class);
    Call<String> signin = service.jquery();

    Toast.makeText(this, signin.toString(), Toast.LENGTH_LONG).show();

我实际上只是尝试使用 GET 请求查询 jquery.org/projects 并返回它响应的字符串.怎么了?

I'm literally just trying to query jquery.org/projects with a GET request and return the String that it responds with. What is wrong?

如果我尝试实现自定义转换器(我在网上找到了一些示例),它会抱怨我没有实现抽象方法 convert(F),而这些示例都没有.

If I try to implement a custom Converter (I've found a few examples online) it complains that I didn't implement the abstract method convert(F), which none of the examples do.

谢谢.

推荐答案

将 Retrofit2 和 ScalarsConverterFactory 添加到您的 Retrofit.Builder.

Add Retrofit2 and ScalarsConverterFactory to your Retrofit.Builder.

adapterBuilder = new Retrofit.Builder()
               .addConverterFactory(ScalarsConverterFactory.create())
               .addConverterFactory(GsonConverterFactory.create());

要使用 ScalarsCoverter,请将以下依赖项添加到您的构建 graddle

To use ScalarsCoverter add following dependency to your build graddle

implementation 'com.squareup.retrofit2:converter-scalars:2.9.0' 
implementation 'com.squareup.retrofit2:retrofit:2.9.0' //Adding Retrofit2

For API Call use: 
    Call <String> *****

安卓代码:

.enqueue(new Callback<String>() {
    @Override
    public void onResponse(Call<String> call, Response<String> response) {
        Log.i("Response", response.body().toString());
        //Toast.makeText()
        if (response.isSuccessful()){
            if (response.body() != null){
                Log.i("onSuccess", response.body().toString());
            }else{
                Log.i("onEmptyResponse", "Returned empty response");//Toast.makeText(getContext(),"Nothing returned",Toast.LENGTH_LONG).show();
            }
        }

这篇关于如何从 Retrofit2 获取字符串响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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