【发布时间】:2016-10-10 03:31:58
【问题描述】:
我使用 Java 和 Jersey 开发了一个 Web 服务。现在我正在尝试使用 android 连接到它,调用它的方法并获取数据。
下面是web服务的相关部分。
import bean.PatientBean;
import bean.UserBean;
import db.PatientImpl;
import db.PatientInterface;
import db.UserImpl;
import db.UserInterface;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/patient")
public class PatientJSONService
{
@POST
@Path("/getPatientById/{Id}")
@Produces(MediaType.APPLICATION_JSON)
public PatientBean getPatientById(@PathParam("Id")String Id)
{
PatientInterface patinetInterface=new PatientImpl();
PatientBean patientById = patinetInterface.getPatientById(Id);
return patientById;
}
}
在我的 android 应用程序中,我使用Retrofit 2 来调用上述 REST 方法。
private void restCall()
{
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss")
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
YourEndpoints request = retrofit.create(YourEndpoints.class);
Call<PatientBean> yourResult = request.getPatientById("ERTA001");
yourResult.enqueue(new Callback<PatientBean>() {
@Override
public void onResponse(Call<PatientBean> call, Response<PatientBean> response) {
try {
// Log.d("MainActivity", "RESPONSE_A: " + response.body().toString());
Log.d("MainActivity", "RESPONSE: " + response.errorBody().string());
}
catch(Exception e)
{
e.printStackTrace();
}
}
@Override
public void onFailure(Call<PatientBean> call, Throwable t) {
try {
t.printStackTrace();
Log.d("MainActivity", "RESPONSE: "+"FAILED");
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
}
下面是我的EndPoint界面
public interface YourEndpoints {
@POST("patient/getPatientById/{Id}")
Call<PatientBean>getPatientById(@Body String Id);
}
但是,当我运行代码时,我收到了来自 Apache Tomcat Server 的 HTML 响应,基本上是 HTTP Status 405 - Method Not Allowed。
我该如何解决这个问题?
【问题讨论】:
-
如果你手动向 Postman 发出请求会发生什么
-
好问题。但我真的不知道如何为此发出邮递员电话。
-
您的端点在我看来就像一个典型的 GET,您为什么要使用 POST 来检索资源?
-
@TimCastelijns:因为我传递了一个 ID...Anwyay,如果这是 GET,它会工作吗?
-
不管它是否有效,我建议你阅读rest和http请求方法,哪个用于什么,等等。只是一个提示
标签: java android post retrofit retrofit2