在我看来,我并没有真正从 MainActivity调用 URL、网络操作。
- 我确实在另一个类 ProcessData 中调用 url.connect()
- 我确实使用 doInBackground()
- 我确实用 AsyncTask 扩展 ProcessData 类
但异常仍然发生:
public class MainActivity extends ActionBarActivity {
private final String LOG_TAG = MainActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ProcessData test = new ProcessData();
test.doInBackground("mysql") ;
}
//separate file ProcessData.java
public class ProcessData extends AsyncTask<String, Void, String> {
public String createValidUrl(String s){
.....//code in this method works fine
}
public String doInBackground(String ...params){
String validUrl = createValidURL(params[0]);
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
URL url = new URL(validUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
urlConnection.disconnect();
reader.close();
return buffer.toString();
}
}
网络主线程异常仍然发生,我阅读了其他 SO 帖子。我可以将我的 http 连接代码包装到新线程中,但我想找出问题所在