我正在尝试将我的 Android 设备上的 POST 方法调用到我的 Java EE Web 应用程序。Java 版本 8,Android 应用程序在 API 级别 22 上,我在我的计算机上使用虚拟设备。我可以将请求添加到 Volley-queue,但它不能解决我的 POST 请求。
这是 Java EE 应用程序上的 CustomerService:
@EJB
CustomerBean customerBean;
@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("/registration")
public Long registration(@FormParam("email") String email, @FormParam("password") String pw) {
Customer c = customerBean.registration(email, pw);
if(c == null) {
return (long) 0;
}
return c.getId();
}
这是 CustomerBean 上的调用方法:
@PersistenceContext
private EntityManager em;
public Customer registration(String email, String password) {
Customer c = (Customer) em.createQuery("FROM " + Customer.class.getSimpleName() + " c WHERE c.email = :email")
.setParameter("email", email).getSingleResult();
if(c == null) {
c = new Customer();
c.setEmail(email);
c.setPassword(password);
em.persist(c);
em.flush();
return c;
}
else {
return null;
}
}
这是我的 Android 客户端,它正在发送 POST 请求(MainActivity):
private Long api_regist(final String email, final String password) throws IOException {
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://10.0.2.2:8080/onlineshop-web/api/customer/registration";
final String[] result = new String[1];
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
@Override
public void onResponse(String response) {
// response
Log.d("Response", response);
result[0] = response;
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}
) {
@Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("password", password);
return params;
}
};
queue.add(postRequest);
while (result[0] == null){
Log.d("Result:", " Empty");
} //TODO return value afterwards
所以结果[0]总是空的。