我尝试在Android下开发。现在,我尝试使用网络。
我有“经理班”
private String makeQuery(String string){
Log.d("makeQuery", "in");
try{
NetTask a = new NetTask(server_url);
}catch(IOException e){
Log.d("makeQuery", "exception");
}
Log.d("makeQuery", "out");
return "string";
}
它具有通过HTTP查询到我自己的API服务器的方法。它使用NetTask对象,NetTask继承AsyncTask
public class NetTask extends AsyncTask<String, Void, Void> {
HttpURLConnection connection;
public NetTask(URL server) throws IOException{
Log.d("NetTask", "Create");
connection = (HttpURLConnection)server.openConnection();
connection.setReadTimeout(10000);
connection.setConnectTimeout(15000);
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setDoOutput(true);
Log.d("NetTask", "Connect");
connection.connect();
Log.d("NetTask", "Response");
int response = connection.getResponseCode();
Log.d("NetTask", "The response is: " + response);
}
就我而言,我得到下一个日志:
[makeQuery]
在
[NetTask]
创建
连接
所以,为什么要行Log.d(“ makeQuery”,“ out”);无法到达?
最佳答案
为什么Log.d("makeQuery", "out");
无法访问?
try{
NetTask a = new NetTask(server_url);
}catch(IOException e){
Log.d("makeQuery", "exception");
}
原因是
NetTask
类引发其他类型的异常。您将更改为
}catch(Exception e){
Log.d("makeQuery", "exception");
}
但好的做法是捕获正确的Exception,对异常处理进行注释,并在LogCat中查找Exception类型。