我是第一次使用Retrofit2,但遇到了一些问题。
这是用于调用REST API的代码段
//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。我收到内部服务器错误。该API无法读取JSON请求。但是,如果我通过Postman访问API,它将返回响应。有什么建议么?
香港专业教育学院添加了邮递员的请求截图。
从邮递员的屏幕快照中可以看到,您正在将JSON正文发送到REST API。在邮递员中将身体类型选择为raw
-application/json
时,它会自动包括
Content-Type:application/json
作为标题。因此,该请求在邮递员中成功。
现在,为了使其能够成功在Android应用程序中的请求之上运行,您需要使用发送到REST API的请求来设置标头。
在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
。当您请求API时,@Body
注释会将(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();
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句