1

伙计们,我在我的 PC 上运行了一个 Web 服务,最近我从 2.2 更改了我的应用程序。对于 4.0,之后我无法再连接到我的 WS。

我正在寻找答案,但一无所获。

我的应用程序引用这样的 URL http://10.0.2.2:8080...但它不起作用。

这是我的代码:

private static final String URL_WS = "[this is not a link]http://10.0.2.2:8080/WS_TaxiShare/)";


public String login(String email, String password) throws Exception {

    String[] resposta = new WSClient().get(URL_WS + "login/login/?login="+ email +"&password="+ password);

    String saida = resposta[1];
    if (resposta[0].equals("200")) {
        return saida;
    } else {
        return saida;
    }
}

现在 WSClient

public class WSClient {

public final String[] get(String url) {

    String[] result = new String[2];
    HttpGet httpget = new HttpGet(url);
    HttpResponse response;

    try {
        Log.i("Get taxi", "Url -> " + url);
        response = HttpClientSingleton.getHttpClientInstace().execute(httpget);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            result[0] = String.valueOf(response.getStatusLine().getStatusCode());
            InputStream instream = entity.getContent();
            result[1] = toString(instream);
            instream.close();
            Log.i("get", "Result from post JsonPost : " + result[0] + " : " + result[1]);
        }
    } catch (Exception e) {
        Log.i("Exception no get WS taxi", "Exception ->" + e);
        result[0] = "0";
        result[1] = "Falha de rede!";
    }
    return result;
}

有人可以帮助我吗?

PS:我的 WS 在 Glassfish 上运行

4

1 回答 1

1

好吧,我可以解决我的问题。Android 4.0(不知道什么时候开始),不能在主线程调用webservices。您需要做的就是创建一个异步方法来在单独的线程中执行您需要的操作。

这是我的方法

private class loginTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... urls) {
        String response = "";


        try {
            //Pegando o email e a senha da tela
            String login = loginLogin.getText().toString();
            String password = loginSenha.getText().toString();

            WSTaxiShare ws = new WSTaxiShare();

            Log.i("inciando login taxi", "Login -> " + login + " Senha -> " + password);
            response = ws.login(login, password);
            Log.i("String resposta taxi", response + "");


        } catch (Exception e) {
            Log.i("Exception Login taxi", e + "");
            gerarToast("Não Foi possível logar");
            e.printStackTrace();
        }


        return response;
    }

    @Override
    protected void onPostExecute(String strJson) {

        try {
            ...
        } catch (JSONException e) {
            ...
        }

    }


}

这是通话按钮:

btnLogin.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            loginTask task = new loginTask();
            task.execute(new String[] { "" });

        }
    });
于 2013-08-17T17:24:47.753 回答