如何从Retrofit2获取字符串响应? [英] How to get string response from 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并返回String它回应。有什么问题?
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?
如果我尝试实现一个自定义转换器(我在网上找到了一些例子)它抱怨我没有实现抽象方法转换( 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。
With Retrofit2 add ScalarsConverterFactory to your Retrofit.Builder.
adapterBuilder = new Retrofit.Builder()
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create());
使用ScalarsCoverter将以下依赖项添加到构建级别
To use ScalarsCoverter add following dependency to your build graddle
compile 'com.squareup.retrofit2:converter-scalars:2.1.0'
compile 'com.squareup.retrofit2:retrofit:2.1.0' //Adding Retrofit2
对于API使用:``
Call <String> *****
Android代码:
Android Code :
.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屋!