伙计们,我的 PC 上运行着一个 Web 服务,最近我从 2.2 更改了我的应用程序。对于 4.0,之后我无法再连接到我的 WS。
我正在寻找答案,但一无所获。
我的应用程序引用了这样的 URLhttp://10.0.2.2:8080
... 但它不起作用。
这是我的代码:
private static final String URL_WS = "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;
}
最佳答案
好吧,我可以解决我的问题。 Android 4.0(不知道什么时候开始),不能在主线程调用webservices。您需要做的就是创建一个异步方法来在单独的线程中执行您需要的操作。
这是我的方法
private class loginTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String response = "";
try {
WSTaxiShare ws = new WSTaxiShare();
response = ws.login(login, password);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
@Override
protected void onPostExecute(String strJson) {
}
这是通话按钮
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
loginTask task = new loginTask();
task.execute(new String[] { "" });
}
});
关于android - 安息在 Android 4.0 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18877480/