I am trying to do a simple application where I have:
(Server) - Jersey RESTful
(Client) - Android
I am trying to make them to communicate via JSON, I have seen several materials, but I still couldn't do it.
Follow my codes. If someone can help me. I am very pleased
Server Code:
@POST
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public void consomeJson(Gson json) {
System.out.println(json);
}
Client code:
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();
}
}
Thanks in advance.
It looks like you are making an HTTP request on the UI thread, which Android isn't going to like. You should at least use an AsyncTask . More info here on network operations.
Also, make sure you are including the network permissions in your manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Check out Android's new Volley library as well. It is supposed to make network requests much simpler. There's a tutorial here and some more info in the Google IO talk .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.