我开发了一个使用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;
}
}
在我的安卓应用程序中,我正在使用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
.
如何解决此问题?
将 ws 终结点更改为 @GET,然后将 rest 客户端更改为以下代码:
@GET("patient/getPatientById/{Id}")
Call<PatientBean>getPatientById(@Path("Id") String Id);
GET 应该用于从服务器检索数据。应使用 POST 将数据发送到服务器。
如果您将 GSON 与 RetroFit 一起使用,则在 getPatientById()
中不需要自己的实现。而且,是的,您应该使用GET
方法。
public interface PatientService {
@GET("patient/getPatientById/{Id}")
Call<PatientBean> getPatientById(@Path("Id") String id);
}
如果PatientBean
设置正确,您应该能够调用以下内容来获取类的完全格式实例:
PatientService service = retrofit.create(PatientService.class);
Call<PatientBean> call = service.getPatientById("ERTA001");
call.enqueue(new Callback<PatientBean> {
@Override
public void onResponse(Call<PatientBean> call, Response<PatientBean> response) {
mPatientBean = response.body();
}
@Override
public void onFailure(Call<PatientBean> call, Throwable throwable) {
throwable.printStackTrace();
}
});