0

我正在尝试做一个简单的应用程序:

(服务器) - Jersey RESTful

(客户端) - 安卓

我正在尝试让它们通过 JSON 进行通信,我看过一些材料,但我仍然无法做到。

遵循我的代码。如果有人可以帮助我。我很高兴

服务器代码:

  @POST
  @Consumes({ MediaType.APPLICATION_JSON })
  @Produces({ MediaType.APPLICATION_JSON })
  public void consomeJson(Gson json) {
      System.out.println(json);
  }

客户端代码:

public void onBtnSalvarClicked(View view)
{        
    TextView t = (TextView) findViewById(R.id.text);

    TextView nome = (TextView) findViewById(R.id.txtNome);
    TextView login = (TextView) findViewById(R.id.txtLogin);
    TextView senha = (TextView) findViewById(R.id.txtSenha);

    Usuario usuario = new Usuario();
    usuario.setNome(nome.getText().toString());
    usuario.setLogin(login.getText().toString());
    usuario.setSenha(senha.getText().toString());

    Gson gson = new Gson();
    params.put("var", gson.toJson(usuario));

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://192.168.1.2:8080/rest/hello");

    try{
        StringEntity se = new StringEntity(gson.toString());
        httppost.setEntity(se);
        HttpResponse response = httpclient.execute(httppost);
    }
    catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }
}

提前致谢。

4

1 回答 1

1

看起来您正在 UI 线程上发出 HTTP 请求,而 Android 不会喜欢这个请求。您至少应该使用AsyncTask。有关网络操作的更多信息。

此外,请确保您在清单中包含网络权限:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

还可以查看 Android 的新 Volley 库。它应该使网络请求更简单。这里有一个教程,Google IO talk中有更多信息。

于 2013-09-14T06:19:42.607 回答