gpt4 book ai didi

java - 无法从 REST API 获取 JSON 作为字符串

转载 作者:行者123 更新时间:2023-11-29 23:07:52 26 4
gpt4 key购买 nike

我正在尝试从 REST API 获取 JSON 作为字符串。

为此,我将 retrofitscalarConverter 结合使用。我能够传递要获取的 URL,并且我的 retrofit 实例也已成功创建,但我没有从服务器收到任何响应。PS:服务器上没有请求,所以这意味着我的请求没有从我的机器发出。

我是android的新手,请帮助我。

改造实例创建:

Retrofit retrofit=new Retrofit.Builder()
.baseUrl(base)
.addConverterFactory(ScalarsConverterFactory.create())
.build();
jsonApi jsonapi=retrofit.create(jsonApi.class);
Call<String> stringcall=jsonapi.getStringResponse(speech);

jsonApi接口(interface):

public interface jsonApi {
@GET
Call<String> getStringResponse(@Url String url);
}

base:它是基本 URL

speech:它是一个变量,包含要处理的 URL 的其余部分。

当我运行时,应用程序卡在此处并在运行选项卡中显示此消息:

W/OpenGLRenderer: Fail to change FontRenderer cache size, it already initialized
W/art: Before Android 4.1, method int android.support.v7.widget.DropDownListView.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView

最佳答案

下面一行

Call<String> stringcall=jsonapi.getStringResponse(speech);

你只是得到一个 Call 对象,它是 HTTP 请求的表示,仅此而已,请求不会被执行。您需要使用此对象并调用execute 方法进行同步请求或调用enqueue 方法进行异步请求。

因此,如果您想发出同步请求,请尝试以下操作:

Retrofit retrofit=new Retrofit.Builder()
.baseUrl(base)
.addConverterFactory(ScalarsConverterFactory.create())
.build();
jsonApi jsonapi=retrofit.create(jsonApi.class);
Call<String> stringcall=jsonapi.getStringResponse(speech);
try {
Response<String> response = stringcall.execute();
String result = response.body();
} catch (Exception ex) {
//handle exception
}

Call接口(interface)的文档是here ,供大家引用。

关于java - 无法从 REST API 获取 JSON 作为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56342641/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com