从Android本地调用由NetBeans IDE生成的RESTful Web服务?

因此,NetBeans IDE可以从数据库生成RESTful Web Service(该表已打包到实体类中)。 我遵循了本教程,并成功生成了RESTful Web服务。

现在,我想从我的Android应用程序打电话,但到目前为止没有运气。 我使用“Android异步Http客户端基于回调的Http Client Library for Android”

所以这是我的代码片段:

customActionBarView.findViewById(R.id.actionbar_done).setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // "Done" String id = generateId(); EditText number = (EditText) findViewById(R.id.caller_phone_number); EditText information = (EditText) findViewById(R.id.caller_information); checkAvailability(id, number.getText().toString(), information.getText().toString()); finish(); } }); 

和这个:

  public void processWebServices(RequestParams params) { AsyncHttpClient client = new AsyncHttpClient(); client.post("http://localhost:8080/AndroidRESTful/com.erikchenmelbourne.entities.caller/create", params, new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] response) { try { JSONObject obj = new JSONObject(response.toString()); if (obj.getBoolean("status")) { setDefaultValues(); Toast.makeText(getApplicationContext(), "Information has been sent!", Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), obj.getString("error_msg"), Toast.LENGTH_LONG).show(); } } catch (JSONException e) { Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response is invalid]!", Toast.LENGTH_LONG).show(); e.printStackTrace(); } } @Override public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) { if (i == 404) { Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show(); } else if (i == 500) { Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]", Toast.LENGTH_LONG).show(); } } }); } 

这是NetBeans IDE生成的POST方法:

  @Path("/create") @POST @Consumes({"application/xml", "application/json"}) public void create(@QueryParam("id") int id, @QueryParam("number") String number, @QueryParam("information") String information) { Caller entity = new Caller (id, number, information); super.create(entity); } 

我添加了@Path(“/ create”)注释并稍微修改了方法。

请说清楚,我对此很新,所以我没有任何线索。 我知道这是由于一些非常愚蠢的错误,但请帮忙。 程序停在

“发生意外错误![最常见错误:设备可能未连接到Internet或远程服务器未启动并运行]”

。 很明显,我无法很好地连接这两个程序。

您的HTTP URL是“ http:// localhost:8080 / …”,即它希望到达在Android设备上运行的服务器。 如果您的IDE /服务正在您的工作站上运行,那么:

  • 如果您在Genymotion模拟器上运行应用程序,请使用10.0.3.2而不是localhost
  • 如果您在SDK模拟器上运行应用程序,请使用10.0.2.2而不是l ocalhost
  • 如果您在真实设备上运行应用程序,则替换工作站的IP地址,并确保设备和工作站位于同一网络上。

参考文献:

  • 如何从Genymotion android模拟器访问localhost
  • 模拟器网络