Android ICS中HttpUrlConnection调用getResponseCode时应用崩溃求助
Hey there! Let's break down your problem step by step—this is super common for folks new to Android, so don't worry!
Your app is crashing almost certainly because you're running network operations on the main (UI) thread. Starting from Android 3.0 (API 11), the system strictly blocks network calls on the main thread—this prevents your app from freezing or becoming unresponsive (ANR) while waiting for network responses. The setText("Checking...") works fine because that's a UI operation, which belongs on the main thread, but urlConnection.getResponseCode() is a network IO task that must run in a background thread.
Another quick check: make sure you've added the internet permission to your AndroidManifest.xml—without this, network requests will fail entirely:
<uses-permission android:name="android.permission.INTERNET"/>
For new Android developers, AsyncTask is a straightforward way to handle background work and update the UI safely (it's a bit old-school, but perfect for learning the thread model). Here's a adapted example for your code:
public class YourActivity extends AppCompatActivity { private TextView t; // Assume this is your text view public void sendMessage(View view) { t.setText("Checking..."); // Launch the background task new NetworkRequestTask().execute(); } // AsyncTask params: [Input type, Progress update type, Result type] private class NetworkRequestTask extends AsyncTask<Void, Void, String> { @Override protected String doInBackground(Void... voids) { // This runs in a background thread—safe for network calls String responseResult = ""; HttpURLConnection urlConnection = null; try { URL targetUrl = new URL("YOUR_WEB_SERVICE_URL"); urlConnection = (HttpURLConnection) targetUrl.openConnection(); urlConnection.setRequestMethod("GET"); // Use POST if your service requires it urlConnection.connect(); // Get response code (this was crashing your app before) int responseCode = urlConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // Read the response content BufferedReader reader = new BufferedReader( new InputStreamReader(urlConnection.getInputStream()) ); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); } responseResult = sb.toString(); } else { responseResult = "Request failed. Code: " + responseCode; } } catch (IOException e) { e.printStackTrace(); responseResult = "Network error: " + e.getMessage(); } finally { // Always clean up the connection if (urlConnection != null) { urlConnection.disconnect(); } } return responseResult; } @Override protected void onPostExecute(String result) { // This runs back on the main thread—safe to update UI here t.setText(result); } } }
- Never skip permissions: Always add
INTERNETpermission when working with web services—this is a super easy mistake to make. - Separate UI and work: Main thread = UI updates only. Background threads = all slow tasks (network, file reading, heavy calculations).
- Update UI safely: Only modify UI elements from the main thread.
AsyncTask'sonPostExecutemethod handles this automatically for you.
As you get more comfortable, you can explore modern alternatives like Kotlin Coroutines (if you're using Kotlin) or ExecutorService + Handler for Java, but mastering this basic thread pattern first will help you avoid tons of common crashes.
内容的提问来源于stack exchange,提问作者Mathews Mathai

