我有一个典型的 Retrofit API 请求。我使用了 vb.net API 调用,它返回如下响应。
<string xmlns="http://tempuri.org/"> {"UserTickets":[{"Type":"Application","Category":"Mobile App","Sub Category":"Other","Issue Details":"Dummy","LMDT":"2019-11-14 15:46:00.000","ResponsibleEmail":"<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="94f5f8f1ecd4f3fbf6f5baf7fbf9" rel="noreferrer noopener nofollow">[email protected]</a>"}],"success":"true","status:":"1"}</string>
我无法使用以下代码获取响应正文。如何从响应对象中获取响应主体?有人可以帮助我吗? API调用Android代码如下:
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
Gson gson = new GsonBuilder()
.setLenient()
.create();
mRetrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
CryptocurrencyService scalarService = mRetrofit.create(CryptocurrencyService.class);
Call<String> stringCall = scalarService.getStringResponse("800028");
stringCall.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
if (response.isSuccessful()) {
String responseString = response.body().toString();
// todo: do something with the response string
Log.e("TAG_RESPONSE", responseString);
}
}
@Override
public void onFailure(Call<String> call, Throwable t) {
}
});
最佳答案
问题是您的响应不是 JSON,这就是您无法获得响应的原因。
相反,如果您的响应是纯字符串,您应该添加一个 Retrofit 标量转换器 com.squareup.retrofit2:converter-scalars:2.5.0
,您可以查看示例 here .
或者,如果您想将响应作为 XML 处理,您应该添加此转换器 compile 'com.squareup.retrofit2:converter-jaxb:2.4.0
关于android - 如何在Retrofit中解析Restful api JSON响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59007403/