我第一次使用Retrofit2,有一些问题。
这是用来调用REST的代码片段
//building retrofit object
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.0.71:9000/api/uniapp/")
.addConverterFactory(GsonConverterFactory.create())
.addConverterFactory(ScalarsConverterFactory.create())
.build();
APIService service = retrofit.create(APIService.class);
//defining the call
Call<String> call = service.refreshAppMetaConfig("0");
//calling the api
call.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
//displaying the message from the response as toast
System.out.println("Uniapp :"+response);
}
@Override
public void onFailure(Call<String> call, Throwable t) {
System.out.println("Uniapp :"+t.getMessage());
}
});
这是APIService类:
public interface APIService {
//The register call
@FormUrlEncoded
@POST("appmetaconfigjson")
Call<String> refreshAppMetaConfig(@Field("versionId") String versionId);
}
我使用Play框架创建REST。我得到了一个内部服务器错误。API无法读取JSON请求。但是如果我通过Postman访问API,它将返回响应。有什么建议吗?
我添加了邮递员请求截图。
发布于 2018-09-01 05:29:12
正如我从您的Postman屏幕截图中看到的,您正在发送JSON body到REST API。当您在邮递员中选择body类型为raw
- application/json
时,它自动包括
Content-Type:application/json
作为头像。因此,这一请求在邮递员中是成功的。
现在,为了使它在Android应用程序中成功地运行在上面的请求中,您需要使用发送到REST的请求来设置头。
在APIService
接口中进行以下更改。
import retrofit2.http.Body;
import okhttp3.ResponseBody;
import java.util.Map;
public interface APIService {
//The register call
// @FormUrlEncoded <==== comment or remove this line
@Headers({
"Content-Type:application/json"
})
@POST("appmetaconfigjson")
Call<ResponseBody> refreshAppMetaConfig(@Body Map<String, String> versionId);
}
@FormUrlEncoded
注释,因为我们发送的是JSON而不是FormUrlEncoded数据。@Headers()
添加Content-Type:application/json
注释@Body Map<String, String> versionId
。@Body
注释在请求API时将Map
(HashMap)数据转换为JSON。String
更改为ResponseBody
。使用上面修改的方法如下所示
// code...
//defining the call
// create parameter with HashMap
Map<String, String> params = new HashMap<>();
params.put("versionId", "0");
Call<ResponseBody> call = service.refreshAppMetaConfig(params);
//calling the api
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
//displaying the message from the response as toast
// convert ResponseBody data to String
String data = response.body().string();
System.out.println("Uniapp : " + data);
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
System.out.println("Uniapp : " + t.getMessage());
}
});
这里还需要将参数从Call<String>
更改为Call<ResponseBody>
。并使用onResponse()
方法转换response.body().string();
方法中的响应。
https://stackoverflow.com/questions/52110913
复制相似问题