实际上我在应用程序中工作,但我在连接 Web 服务时遇到问题,我有以下代码:
try{
HttpServices post = new HttpServices ("http://sotem.com.mx/WebServices/controller.php");
post.add("funcion", "test");
System.out.println("Si lo mande///////////////////Jhgfdsa");
String respuesta = post.getRespueta();
System.out.println(respuesta);
Toast.makeText(getApplicationContext(),"Cool: "+respuesta, Toast.LENGTH_SHORT).show();
}catch (Exception ex) {
Toast.makeText(getApplicationContext(),"error: "+ex.toString(), Toast.LENGTH_SHORT).show();
}
但我可以建立连接,我尝试做出其他想法,但我可以建立线程,我是这部分的新手,应用程序启动器出现此错误:
主线程上的 Android 操作系统网络异常
最佳答案
在主线程上进行网络操作是不行的。您可以使用 AsyncTask执行此类操作并在 onPostExecute
方法中处理结果。
class YourNetworkingTasks extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... voids) {
try{
HttpServices post = new HttpServices ("http://sotem.com.mx/WebServices/controller.php");
post.add("funcion", "test");
String respuesta = post.getRespueta();
Log.d("Output", respuesta);
// DON'T DO ANY UI CHANGES LIKE TOAST FROM BACKGROUND THREAD.. Toast.makeText(getApplicationContext(),"Cool: "+respuesta, Toast.LENGTH_SHORT).show();
}catch (Exception ex) {
// DON'T DO ANY UI CHANGES LIKE TOAST FROM BACKGROUND THREAD.. Toast.makeText(getApplicationContext(),"error: "+ex.toString(), Toast.LENGTH_SHORT).show();
}
return null;
}
protected void onPostExecute(RSSFeed feed) {
// TODO: YOU CAN MAKE U.I. Changes Like Display text in TextView, TOAST HERE.
// TODO: do something with the result
}
}
并编写new YourNetworkingTasks().execute();
以在后台线程中运行该代码。
另请注意,由于您使用的是 http 而不是 https,您可能会得到 Network Security Exception由于 Android 最近的安全更改,可能无法获得任何输出。
关于java - 当我尝试将我的应用程序连接到网络服务时失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55463853/