简体   繁体   English

通过JSON Rest Server(Jersey)和Android进行通信

[英]Communicating by JSON Rest Server (Jersey) and Android

I am trying to do a simple application where I have: 我正在尝试做一个简单的应用程序,其中:

(Server) - Jersey RESTful (服务器)-泽西RESTful

(Client) - Android (客户端)-Android

I am trying to make them to communicate via JSON, I have seen several materials, but I still couldn't do it. 我正在尝试使他们通过JSON进行通信,我已经看过几种材料,但是我仍然做不到。

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. 看来您是在UI线程上发出HTTP请求,而Android不会。 You should at least use an AsyncTask . 您至少应使用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. 还可以查看Android的新Volley库。 It is supposed to make network requests much simpler. 它应该使网络请求简单得多。 There's a tutorial here and some more info in the Google IO talk . 有一个教程在这里和一些更多的信息的谷歌IO谈话

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM