用okhttp3就能正常返回json,但用retrofit2返回的就是网页内容,这是为什么?

新手上路,请多包涵

如题,retrofit2返回的就是网页内容,用okhttp3就能正常返回json,下面是运行代码。

retrofit2

public interface Api {
    @HTTP(method = "GET",path = "/")
    @Headers({
            "accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
            "user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36"
    })
    Call<ResponseBody> getData();
}
public class Test {
    public static void main(String[] args) {
        Retrofit retrofit = new Retrofit.Builder()
//              .addConverterFactory(GsonConverterFactory.create())
                .baseUrl("https://api.lolicon.app/setu/v2/") // api地址
                .build();
        Api api = retrofit.create(Api.class);
        Call<ResponseBody> data = api.getData();

        data.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                System.out.println("返回成功");
                try {
                    System.out.println(response.body().string()); // 访问成功,但是返回的是网页内容
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                System.out.println("返回失败");
                System.out.println(t.getMessage());
            }
        });
    }
}

OKhttp3

public class Test2 {
    public static void main(String[] args) {
        String url = "https://api.lolicon.app/setu/v2/";
        OkHttpClient okHttpClient = new OkHttpClient();
        Request build = new Request.Builder().url(url).get().build();
        Call call = okHttpClient.newCall(build);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                System.out.println("失败了");
                System.out.println(e.getMessage());
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                System.out.println(response.body().string()); // 能正常返回
            }
        });
    }
}
阅读 1.4k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏