我正在尝试做一个简单的应用程序,我有:
(服务器) - 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();
}
}
提前致谢。
最佳答案
看起来您正在 UI 线程上发出 HTTP 请求,Android 不会喜欢这种情况。您至少应该使用 AsyncTask 。更多信息here关于网络操作。
此外,请确保在 list 中包含网络权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
还可以查看 Android 的新 Volley 库。它应该使网络请求变得更加简单。有教程here以及 the Google IO talk 中的更多信息.
关于java - 通过 JSON Rest Server (Jersey) 和 Android 进行通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18795130/