Android Java 网络编程示例

Android Java 网络编程示例,包括HTTP请求、文件下载上传和WebSocket连接

💻 HTTP请求 java

🟢 simple ⭐⭐⭐

使用HttpURLConnection发送GET和POST请求,具有适当的错误处理和响应处理

⏱️ 30 min 🏷️ java, android, networking, http
Prerequisites: Basic Java knowledge, Internet permission in manifest
// Android Java HTTP Request Examples
// Using HttpURLConnection and OkHttp

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import java.io.*;
import java.net.*;
import java.util.*;
import org.json.JSONObject;

// 1. HttpURLConnection Examples
public class HttpURLConnectionExample {
    private Context context;

    public HttpURLConnectionExample(Context context) {
        this.context = context;
    }

    // Simple GET request
    public interface StringCallback {
        void onSuccess(String result);
        void onError(String error);
    }

    public void simpleGetRequest(String url, final StringCallback callback) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL urlObj = new URL(url);
                    connection = (HttpURLConnection) urlObj.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(10000);
                    connection.setReadTimeout(10000);

                    int responseCode = connection.getResponseCode();
                    System.out.println("Response Code: " + responseCode);

                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        BufferedReader reader = new BufferedReader(
                            new InputStreamReader(connection.getInputStream())
                        );
                        StringBuilder response = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            response.append(line);
                        }
                        reader.close();

                        final String result = response.toString();
                        System.out.println("Response: " + result);

                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                callback.onSuccess(result);
                            }
                        });
                    } else {
                        final String error = "Error response code: " + responseCode;
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                callback.onError(error);
                            }
                        });
                    }
                } catch (Exception e) {
                    final String error = "GET Request Error: " + e.getMessage();
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onError(error);
                        }
                    });
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    // POST request with JSON body
    public void postJsonRequest(String url, JSONObject jsonData, final StringCallback callback) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL urlObj = new URL(url);
                    connection = (HttpURLConnection) urlObj.openConnection();
                    connection.setRequestMethod("POST");
                    connection.setRequestProperty("Content-Type", "application/json");
                    connection.setDoOutput(true);

                    // Write JSON body
                    OutputStream outputStream = connection.getOutputStream();
                    outputStream.write(jsonData.toString().getBytes("UTF-8"));
                    outputStream.flush();
                    outputStream.close();

                    int responseCode = connection.getResponseCode();
                    System.out.println("POST Response Code: " + responseCode);

                    if (responseCode == HttpURLConnection.HTTP_OK ||
                        responseCode == HttpURLConnection.HTTP_CREATED) {

                        BufferedReader reader = new BufferedReader(
                            new InputStreamReader(connection.getInputStream())
                        );
                        StringBuilder response = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            response.append(line);
                        }
                        reader.close();

                        final String result = response.toString();
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                callback.onSuccess(result);
                            }
                        });
                    } else {
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                callback.onError("POST failed with code: " + responseCode);
                            }
                        });
                    }
                } catch (Exception e) {
                    final String error = "POST Request Error: " + e.getMessage();
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onError(error);
                        }
                    });
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    // POST request with form data
    public void postFormData(String url, Map<String, String> params, final StringCallback callback) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL urlObj = new URL(url);
                    connection = (HttpURLConnection) urlObj.openConnection();
                    connection.setRequestMethod("POST");
                    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    connection.setDoOutput(true);

                    // Build form data
                    StringBuilder formData = new StringBuilder();
                    boolean first = true;
                    for (Map.Entry<String, String> entry : params.entrySet()) {
                        if (!first) {
                            formData.append("&");
                        }
                        formData.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
                        formData.append("=");
                        formData.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
                        first = false;
                    }

                    OutputStream outputStream = connection.getOutputStream();
                    outputStream.write(formData.toString().getBytes("UTF-8"));
                    outputStream.flush();
                    outputStream.close();

                    int responseCode = connection.getResponseCode();
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        BufferedReader reader = new BufferedReader(
                            new InputStreamReader(connection.getInputStream())
                        );
                        StringBuilder response = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            response.append(line);
                        }
                        reader.close();

                        final String result = response.toString();
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                callback.onSuccess(result);
                            }
                        });
                    } else {
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                callback.onError("Form POST failed: " + responseCode);
                            }
                        });
                    }
                } catch (Exception e) {
                    final String error = "Form POST Error: " + e.getMessage();
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onError(error);
                        }
                    });
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    // GET request with headers
    public void getRequestWithHeaders(String url, Map<String, String> headers, final StringCallback callback) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL urlObj = new URL(url);
                    connection = (HttpURLConnection) urlObj.openConnection();
                    connection.setRequestMethod("GET");

                    // Add custom headers
                    for (Map.Entry<String, String> entry : headers.entrySet()) {
                        connection.setRequestProperty(entry.getKey(), entry.getValue());
                    }

                    int responseCode = connection.getResponseCode();
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        BufferedReader reader = new BufferedReader(
                            new InputStreamReader(connection.getInputStream())
                        );
                        StringBuilder response = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            response.append(line);
                        }
                        reader.close();

                        final String result = response.toString();
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                callback.onSuccess(result);
                            }
                        });
                    } else {
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                callback.onError("GET with Headers failed: " + responseCode);
                            }
                        });
                    }
                } catch (Exception e) {
                    final String error = "GET with Headers Error: " + e.getMessage();
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onError(error);
                        }
                    });
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }
}

// 2. REST API Client
public class RestClient {
    private String baseUrl;
    private Context context;

    public RestClient(String baseUrl, Context context) {
        this.baseUrl = baseUrl;
        this.context = context;
    }

    public void get(String endpoint, final StringCallback callback) {
        String url = baseUrl + endpoint;
        new HttpURLConnectionExample(context).simpleGetRequest(url, callback);
    }

    public void post(String endpoint, JSONObject data, final StringCallback callback) {
        String url = baseUrl + endpoint;
        new HttpURLConnectionExample(context).postJsonRequest(url, data, callback);
    }
}

// 3. Advanced HTTP Operations
public class AdvancedHttpExample {
    private Context context;

    public AdvancedHttpExample(Context context) {
        this.context = context;
    }

    // Request with timeout
    public void requestWithTimeout(String url, int timeoutSeconds, final StringCallback callback) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL urlObj = new URL(url);
                    connection = (HttpURLConnection) urlObj.openConnection();
                    connection.setConnectTimeout(timeoutSeconds * 1000);
                    connection.setReadTimeout(timeoutSeconds * 1000);

                    int responseCode = connection.getResponseCode();
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        BufferedReader reader = new BufferedReader(
                            new InputStreamReader(connection.getInputStream())
                        );
                        StringBuilder response = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            response.append(line);
                        }
                        reader.close();

                        final String result = response.toString();
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                callback.onSuccess(result);
                            }
                        });
                    } else {
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                callback.onError("Timeout Error: " + responseCode);
                            }
                        });
                    }
                } catch (Exception e) {
                    final String error = "Timeout Error: " + e.getMessage();
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onError(error);
                        }
                    });
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    // Retry mechanism
    public void requestWithRetry(final String url, final int maxRetries, final long delayMillis, final StringCallback callback) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Exception lastException = null;

                for (int attempt = 0; attempt < maxRetries; attempt++) {
                    try {
                        URL urlObj = new URL(url);
                        HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();

                        int responseCode = connection.getResponseCode();
                        if (responseCode == HttpURLConnection.HTTP_OK) {
                            BufferedReader reader = new BufferedReader(
                                new InputStreamReader(connection.getInputStream())
                            );
                            StringBuilder response = new StringBuilder();
                            String line;
                            while ((line = reader.readLine()) != null) {
                                response.append(line);
                            }
                            reader.close();

                            final String result = response.toString();
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    callback.onSuccess(result);
                                }
                            });
                            return;
                        }

                        connection.disconnect();
                    } catch (Exception e) {
                        lastException = e;
                        System.out.println("Attempt " + (attempt + 1) + " failed: " + e.getMessage());

                        if (attempt < maxRetries - 1) {
                            try {
                                Thread.sleep(delayMillis);
                            } catch (InterruptedException ie) {
                                // Ignore
                            }
                        }
                    }
                }

                final String error = "All " + maxRetries + " attempts failed";
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onError(error);
                    }
                });
            }
        }).start();
    }
}

// 4. Network State Checker
public class NetworkStateChecker {
    private Context context;

    public NetworkStateChecker(Context context) {
        this.context = context;
    }

    public boolean isNetworkAvailable() {
        android.net.ConnectivityManager cm =
            (android.net.ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        android.net.NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    }

    public boolean isWifiConnected() {
        android.net.ConnectivityManager cm =
            (android.net.ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        android.net.NetworkInfo wifiInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        return wifiInfo != null && wifiInfo.isConnected();
    }

    public boolean isMobileConnected() {
        android.net.ConnectivityManager cm =
            (android.net.ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        android.net.NetworkInfo mobileInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        return mobileInfo != null && mobileInfo.isConnected();
    }
}

// Main demonstration
public class HTTPRequestDemo {
    public static void demonstrateHTTPRequests(Context context) {
        System.out.println("=== Android Java HTTP Request Examples ===\n");

        HttpURLConnectionExample httpExample = new HttpURLConnectionExample(context);

        // 1. Simple GET request
        System.out.println("--- 1. Simple GET Request ---");
        httpExample.simpleGetRequest("https://api.example.com/data",
            new HttpURLConnectionExample.StringCallback() {
                @Override
                public void onSuccess(String result) {
                    System.out.println("GET Result: " + result);
                }

                @Override
                public void onError(String error) {
                    System.out.println("GET Error: " + error);
                }
            });

        // 2. POST JSON request
        System.out.println("\n--- 2. POST JSON Request ---");
        try {
            JSONObject jsonData = new JSONObject();
            jsonData.put("key", "value");
            jsonData.put("number", 123);

            httpExample.postJsonRequest("https://api.example.com/post", jsonData,
                new HttpURLConnectionExample.StringCallback() {
                    @Override
                    public void onSuccess(String result) {
                        System.out.println("POST Result: " + result);
                    }

                    @Override
                    public void onError(String error) {
                        System.out.println("POST Error: " + error);
                    }
                });
        } catch (Exception e) {
            System.out.println("JSON Error: " + e.getMessage());
        }

        // 3. POST form data
        System.out.println("\n--- 3. POST Form Data ---");
        Map<String, String> formData = new HashMap<>();
        formData.put("username", "testuser");
        formData.put("password", "pass123");

        httpExample.postFormData("https://api.example.com/login", formData,
            new HttpURLConnectionExample.StringCallback() {
                @Override
                public void onSuccess(String result) {
                    System.out.println("Form POST Result: " + result);
                }

                @Override
                public void onError(String error) {
                    System.out.println("Form POST Error: " + error);
                }
            });

        // 4. REST client
        System.out.println("\n--- 4. REST API Client ---");
        RestClient restClient = new RestClient("https://api.example.com", context);
        restClient.get("/users",
            new HttpURLConnectionExample.StringCallback() {
                @Override
                public void onSuccess(String result) {
                    System.out.println("REST GET Result: " + result);
                }

                @Override
                public void onError(String error) {
                    System.out.println("REST GET Error: " + error);
                }
            });

        // 5. Network state
        System.out.println("\n--- 5. Network State ---");
        NetworkStateChecker networkChecker = new NetworkStateChecker(context);
        System.out.println("Network available: " + networkChecker.isNetworkAvailable());
        System.out.println("WiFi connected: " + networkChecker.isWifiConnected());
        System.out.println("Mobile connected: " + networkChecker.isMobileConnected());

        System.out.println("\n=== All HTTP Request Examples Completed ===");
    }
}

💻 文件下载/上传 java

🟡 intermediate ⭐⭐⭐⭐

下载和上传文件,具有进度跟踪、暂停/恢复功能和后台任务管理

⏱️ 35 min 🏷️ java, android, networking, download, upload
Prerequisites: Intermediate Java, Storage permissions
// Android Java File Download/Upload Examples
// Using DownloadManager and HttpURLConnection

import android.app.DownloadManager;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.webkit.MimeTypeMap;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

// 1. DownloadManager (System-managed downloads)
public class SystemDownloadExample {
    private Context context;
    private DownloadManager downloadManager;

    public SystemDownloadExample(Context context) {
        this.context = context;
        this.downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    }

    // Simple download using DownloadManager
    public long downloadFile(String url, String title, String description) {
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        request.setTitle(title);
        request.setDescription(description);
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);

        // Set destination
        String fileName = url.substring(url.lastIndexOf('/') + 1);
        String extension = MimeTypeMap.getFileExtensionFromUrl(fileName);
        String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        request.setMimeType(mimeType);

        // Save to external storage
        request.setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, fileName);

        return downloadManager.enqueue(request);
    }

    // Query download status
    public int getDownloadStatus(long downloadId) {
        DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
        Cursor cursor = downloadManager.query(query);

        int status = -1;
        if (cursor != null && cursor.moveToFirst()) {
            status = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS));
            cursor.close();
        }

        return status;
    }

    // Get download progress
    public int getDownloadProgress(long downloadId) {
        DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
        Cursor cursor = downloadManager.query(query);

        int progress = 0;
        if (cursor != null && cursor.moveToFirst()) {
            int bytesDownloaded = cursor.getInt(
                cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)
            );
            int bytesTotal = cursor.getInt(
                cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)
            );

            if (bytesTotal > 0) {
                progress = (bytesDownloaded * 100) / bytesTotal;
            }
            cursor.close();
        }

        return progress;
    }

    // Cancel download
    public void cancelDownload(long downloadId) {
        downloadManager.remove(downloadId);
    }
}

// 2. Manual Download with Progress
public class ManualDownloadExample {
    private Context context;

    public ManualDownloadExample(Context context) {
        this.context = context;
    }

    public interface DownloadProgressCallback {
        void onProgress(long bytesRead, long contentLength);
        void onSuccess(File file);
        void onError(String error);
    }

    // Download file with progress callback
    public void downloadFile(String url, File outputFile, final DownloadProgressCallback callback) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL urlObj = new URL(url);
                    connection = (HttpURLConnection) urlObj.openConnection();
                    connection.setConnectTimeout(10000);
                    connection.setReadTimeout(10000);
                    connection.setRequestMethod("GET");

                    int responseCode = connection.getResponseCode();
                    if (responseCode != HttpURLConnection.HTTP_OK) {
                        callback.onError("Server returned HTTP " + responseCode);
                        return;
                    }

                    long contentLength = connection.getContentLengthLong();
                    InputStream inputStream = connection.getInputStream();
                    FileOutputStream outputStream = new FileOutputStream(outputFile);

                    byte[] buffer = new byte[8192];
                    int bytesRead;
                    long totalBytesRead = 0;

                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                        totalBytesRead += bytesRead;

                        final long finalTotalBytesRead = totalBytesRead;
                        callback.onProgress(finalTotalBytesRead, contentLength);
                    }

                    outputStream.flush();
                    outputStream.close();
                    inputStream.close();

                    callback.onSuccess(outputFile);
                } catch (Exception e) {
                    callback.onError("Download Error: " + e.getMessage());
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    // Download state for resumeable downloads
    public static class DownloadState {
        public String url;
        public File outputFile;
        public long downloadedBytes = 0;

        public DownloadState(String url, File outputFile, long downloadedBytes) {
            this.url = url;
            this.outputFile = outputFile;
            this.downloadedBytes = downloadedBytes;
        }
    }

    // Resumeable download
    public void resumeableDownload(final DownloadState state, final DownloadProgressCallback callback) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL urlObj = new URL(state.url);
                    connection = (HttpURLConnection) urlObj.openConnection();

                    // Set range header for resume
                    if (state.downloadedBytes > 0 && state.outputFile.exists()) {
                        connection.setRequestProperty("Range", "bytes=" + state.downloadedBytes + "-");
                    }

                    connection.setConnectTimeout(10000);
                    connection.setReadTimeout(10000);

                    int responseCode = connection.getResponseCode();
                    if (responseCode != HttpURLConnection.HTTP_OK &&
                        responseCode != HttpURLConnection.HTTP_PARTIAL) {
                        callback.onError("Server returned HTTP " + responseCode);
                        return;
                    }

                    long contentLength;
                    if (responseCode == HttpURLConnection.HTTP_PARTIAL) {
                        contentLength = connection.getContentLengthLong() + state.downloadedBytes;
                    } else {
                        contentLength = state.downloadedBytes;
                    }

                    InputStream inputStream = connection.getInputStream();
                    FileOutputStream outputStream;
                    if (state.downloadedBytes > 0) {
                        outputStream = new FileOutputStream(state.outputFile, true);
                    } else {
                        outputStream = new FileOutputStream(state.outputFile);
                    }

                    byte[] buffer = new byte[8192];
                    int bytesRead;
                    long totalBytesRead = state.downloadedBytes;

                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                        totalBytesRead += bytesRead;

                        final long finalTotalBytesRead = totalBytesRead;
                        callback.onProgress(finalTotalBytesRead, contentLength);
                    }

                    outputStream.flush();
                    outputStream.close();
                    inputStream.close();

                    callback.onSuccess(state.outputFile);
                } catch (Exception e) {
                    callback.onError("Resumeable Download Error: " + e.getMessage());
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }
}

// 3. File Upload
public class FileUploadExample {
    private Context context;

    public FileUploadExample(Context context) {
        this.context = context;
    }

    public interface UploadProgressCallback {
        void onProgress(long bytesWritten, long contentLength);
        void onSuccess(String response);
        void onError(String error);
    }

    // Upload single file with progress
    public void uploadFile(String url, File file, final UploadProgressCallback callback) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    String lineEnd = "\r\n";
                    String twoHyphens = "--";
                    String boundary = "*****" + System.currentTimeMillis() + "*****";

                    URL urlObj = new URL(url);
                    connection = (HttpURLConnection) urlObj.openConnection();
                    connection.setDoInput(true);
                    connection.setDoOutput(true);
                    connection.setUseCaches(false);
                    connection.setRequestMethod("POST");
                    connection.setRequestProperty("Connection", "Keep-Alive");
                    connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

                    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());

                    // Upload file
                    outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                    outputStream.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"" + lineEnd);
                    outputStream.writeBytes("Content-Type: " + getMimeType(file) + lineEnd);
                    outputStream.writeBytes(lineEnd);

                    FileInputStream fileInputStream = new FileInputStream(file);
                    byte[] buffer = new byte[8192];
                    int bytesRead;
                    long bytesWritten = 0;
                    long contentLength = file.length();

                    while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                        bytesWritten += bytesRead;
                        callback.onProgress(bytesWritten, contentLength);
                    }

                    fileInputStream.close();
                    outputStream.writeBytes(lineEnd);
                    outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
                    outputStream.flush();

                    int responseCode = connection.getResponseCode();
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                        StringBuilder response = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            response.append(line);
                        }
                        reader.close();

                        callback.onSuccess(response.toString());
                    } else {
                        callback.onError("Upload failed with code: " + responseCode);
                    }

                    outputStream.close();
                } catch (Exception e) {
                    callback.onError("Upload Error: " + e.getMessage());
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    // Upload multiple files
    public void uploadMultipleFiles(String url, File[] files, final UploadProgressCallback callback) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    String lineEnd = "\r\n";
                    String twoHyphens = "--";
                    String boundary = "*****" + System.currentTimeMillis() + "*****";

                    URL urlObj = new URL(url);
                    connection = (HttpURLConnection) urlObj.openConnection();
                    connection.setDoInput(true);
                    connection.setDoOutput(true);
                    connection.setUseCaches(false);
                    connection.setRequestMethod("POST");
                    connection.setRequestProperty("Connection", "Keep-Alive");
                    connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

                    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());

                    for (File file : files) {
                        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                        outputStream.writeBytes("Content-Disposition: form-data; name=\"files\"; filename=\"" + file.getName() + "\"" + lineEnd);
                        outputStream.writeBytes("Content-Type: " + getMimeType(file) + lineEnd);
                        outputStream.writeBytes(lineEnd);

                        FileInputStream fileInputStream = new FileInputStream(file);
                        byte[] buffer = new byte[8192];
                        int bytesRead;
                        while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, bytesRead);
                        }
                        fileInputStream.close();

                        outputStream.writeBytes(lineEnd);
                    }

                    outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
                    outputStream.flush();

                    int responseCode = connection.getResponseCode();
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                        StringBuilder response = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            response.append(line);
                        }
                        reader.close();

                        callback.onSuccess(response.toString());
                    } else {
                        callback.onError("Upload failed with code: " + responseCode);
                    }

                    outputStream.close();
                } catch (Exception e) {
                    callback.onError("Multiple Upload Error: " + e.getMessage());
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    private String getMimeType(File file) {
        String extension = getFileExtension(file).toLowerCase();
        switch (extension) {
            case "jpg":
            case "jpeg":
                return "image/jpeg";
            case "png":
                return "image/png";
            case "gif":
                return "image/gif";
            case "pdf":
                return "application/pdf";
            case "txt":
                return "text/plain";
            case "json":
                return "application/json";
            case "mp4":
                return "video/mp4";
            case "mp3":
                return "audio/mpeg";
            default:
                return "application/octet-stream";
        }
    }

    private String getFileExtension(File file) {
        String name = file.getName();
        int dotIndex = name.lastIndexOf('.');
        return dotIndex > 0 ? name.substring(dotIndex + 1) : "";
    }
}

// Main demonstration
public class FileDownloadUploadDemo {
    public static void demonstrateFileDownloadUpload(Context context) {
        System.out.println("=== Android Java File Download/Upload Examples ===\n");

        // 1. System download
        System.out.println("--- 1. System Download (DownloadManager) ---");
        SystemDownloadExample systemDownload = new SystemDownloadExample(context);

        // Note: Replace with actual URL
        // long downloadId = systemDownload.downloadFile(
        //     "https://example.com/file.pdf",
        //     "File Download",
        //     "Downloading file..."
        // );

        // 2. Manual download with progress
        System.out.println("\n--- 2. Manual Download with Progress ---");
        ManualDownloadExample manualDownload = new ManualDownloadExample(context);

        File outputFile = new File(context.getExternalFilesDir(null), "downloaded_file.pdf");
        // manualDownload.downloadFile(
        //     "https://example.com/file.pdf",
        //     outputFile,
        //     new ManualDownloadExample.DownloadProgressCallback() {
        //         @Override
        //         public void onProgress(long bytesRead, long contentLength) {
        //             int progress = (int) ((bytesRead * 100) / contentLength);
        //             System.out.println("Download progress: " + progress + "%");
        //         }
        //
        //         @Override
        //         public void onSuccess(File file) {
        //             System.out.println("Download completed: " + file.getAbsolutePath());
        //         }
        //
        //         @Override
        //         public void onError(String error) {
        //             System.out.println("Download error: " + error);
        //         }
        //     }
        // );

        // 3. File upload
        System.out.println("\n--- 3. File Upload ---");
        FileUploadExample uploadExample = new FileUploadExample(context);

        File fileToUpload = new File(context.getFilesDir(), "upload.txt");
        // uploadExample.uploadFile(
        //     "https://example.com/upload",
        //     fileToUpload,
        //     new FileUploadExample.UploadProgressCallback() {
        //         @Override
        //         public void onProgress(long bytesWritten, long contentLength) {
        //             int progress = (int) ((bytesWritten * 100) / contentLength);
        //             System.out.println("Upload progress: " + progress + "%");
        //         }
        //
        //         @Override
        //         public void onSuccess(String response) {
        //             System.out.println("Upload response: " + response);
        //         }
        //
        //         @Override
        //         public void onError(String error) {
        //             System.out.println("Upload error: " + error);
        //         }
        //     }
        // );

        System.out.println("\n=== All File Download/Upload Examples Completed ===");
    }
}

💻 WebSocket连接 java

🟡 intermediate ⭐⭐⭐⭐

建立WebSocket连接,发送/接收消息,并处理连接生命周期

⏱️ 30 min 🏷️ java, android, networking, websocket
Prerequisites: Intermediate Java, OkHttp library
// Android Java WebSocket Examples
// Using OkHttp WebSocket client

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import okhttp3.*;
import okio.ByteString;
import org.json.JSONObject;
import java.util.concurrent.TimeUnit;

// 1. Basic WebSocket with OkHttp
public class BasicWebSocketExample {
    private Context context;
    private OkHttpClient client;
    private WebSocket webSocket;

    public BasicWebSocketExample(Context context) {
        this.context = context;
        this.client = new OkHttpClient.Builder()
            .readTimeout(0, TimeUnit.MILLISECONDS)
            .build();
    }

    // Connect to WebSocket
    public void connect(String url) {
        Request request = new Request.Builder()
            .url(url)
            .build();

        WebSocketListener listener = new WebSocketListener() {
            @Override
            public void onOpen(WebSocket webSocket, Response response) {
                System.out.println("WebSocket Connected");
                System.out.println("Server response: " + response.message());

                // Send welcome message
                webSocket.send("Hello from Android!");
            }

            @Override
            public void onMessage(WebSocket webSocket, String text) {
                System.out.println("Received text: " + text);
            }

            @Override
            public void onMessage(WebSocket webSocket, ByteString bytes) {
                System.out.println("Received bytes: " + bytes.hex());
            }

            @Override
            public void onClosing(WebSocket webSocket, int code, String reason) {
                System.out.println("Closing: " + code + " " + reason);
                webSocket.close(code, reason);
            }

            @Override
            public void onClosed(WebSocket webSocket, int code, String reason) {
                System.out.println("WebSocket Closed: " + code + " " + reason);
            }

            @Override
            public void onFailure(WebSocket webSocket, Throwable t, Response response) {
                System.out.println("WebSocket Error: " + t.getMessage());
            }
        };

        webSocket = client.newWebSocket(request, listener);
    }

    // Send text message
    public void sendMessage(String message) {
        if (webSocket != null) {
            webSocket.send(message);
        }
    }

    // Send JSON message
    public void sendJson(JSONObject json) {
        if (webSocket != null) {
            webSocket.send(json.toString());
        }
    }

    // Send binary data
    public void sendBinary(byte[] data) {
        if (webSocket != null) {
            webSocket.send(ByteString.of(data));
        }
    }

    // Close connection
    public void close() {
        if (webSocket != null) {
            webSocket.close(1000, "Goodbye!");
            webSocket = null;
        }
    }
}

// 2. Advanced WebSocket with Reconnection
public class AdvancedWebSocketExample {
    private Context context;
    private OkHttpClient client;
    private WebSocket webSocket;
    private boolean isConnected = false;
    private int reconnectAttempts = 0;
    private final int maxReconnectAttempts = 5;
    private final long reconnectDelay = 3000; // 3 seconds
    private java.util.List<String> messageQueue = new java.util.ArrayList<>();

    public interface WebSocketCallback {
        void onConnected();
        void onMessage(String text);
        void onMessage(ByteString bytes);
        void onDisconnected();
        void onError(String error);
    }

    private WebSocketCallback callback;

    public AdvancedWebSocketExample(Context context, String url) {
        this.context = context;
        this.client = new OkHttpClient.Builder()
            .readTimeout(0, TimeUnit.MILLISECONDS)
            .build();
    }

    public void setCallback(WebSocketCallback callback) {
        this.callback = callback;
    }

    // Connect with auto-reconnect
    public void connect(final String url) {
        Request request = new Request.Builder()
            .url(url)
            .addHeader("Origin", context.getPackageName())
            .build();

        WebSocketListener listener = new WebSocketListener() {
            @Override
            public void onOpen(WebSocket webSocket, Response response) {
                System.out.println("WebSocket Connected");
                isConnected = true;
                reconnectAttempts = 0;

                if (callback != null) {
                    callback.onConnected();
                }

                // Send queued messages
                synchronized (messageQueue) {
                    for (String message : messageQueue) {
                        webSocket.send(message);
                    }
                    messageQueue.clear();
                }
            }

            @Override
            public void onMessage(WebSocket webSocket, String text) {
                System.out.println("Received: " + text);
                if (callback != null) {
                    callback.onMessage(text);
                }
            }

            @Override
            public void onMessage(WebSocket webSocket, ByteString bytes) {
                System.out.println("Received bytes: " + bytes.hex());
                if (callback != null) {
                    callback.onMessage(bytes);
                }
            }

            @Override
            public void onClosing(WebSocket webSocket, int code, String reason) {
                System.out.println("Closing: " + code + " " + reason);
            }

            @Override
            public void onClosed(WebSocket webSocket, int code, String reason) {
                System.out.println("WebSocket Closed: " + code + " " + reason);
                isConnected = false;
                if (callback != null) {
                    callback.onDisconnected();
                }

                // Attempt reconnection
                attemptReconnect(url);
            }

            @Override
            public void onFailure(WebSocket webSocket, Throwable t, Response response) {
                System.out.println("WebSocket Error: " + t.getMessage());
                isConnected = false;
                if (callback != null) {
                    callback.onError(t.getMessage() != null ? t.getMessage() : "Unknown error");
                }

                // Attempt reconnection
                attemptReconnect(url);
            }
        };

        webSocket = client.newWebSocket(request, listener);
    }

    // Attempt reconnection
    private void attemptReconnect(final String url) {
        if (reconnectAttempts < maxReconnectAttempts) {
            reconnectAttempts++;

            new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    System.out.println("Reconnecting... Attempt " + reconnectAttempts);
                    connect(url);
                }
            }, reconnectDelay);
        } else {
            System.out.println("Max reconnection attempts reached");
        }
    }

    // Send message with queueing
    public void sendMessage(String message) {
        if (isConnected && webSocket != null) {
            webSocket.send(message);
        } else {
            // Queue message for later
            synchronized (messageQueue) {
                messageQueue.add(message);
            }
            System.out.println("Message queued: " + message);
        }
    }

    // Close connection
    public void close() {
        reconnectAttempts = maxReconnectAttempts; // Stop reconnection
        if (webSocket != null) {
            webSocket.close(1000, "User closing");
            webSocket = null;
        }
        isConnected = false;
    }
}

// 3. WebSocket Chat Example
public class ChatWebSocket {
    private Context context;
    private OkHttpClient client;
    private WebSocket webSocket;

    public static class ChatMessage {
        public String type; // "join", "message", "leave"
        public String username;
        public String content;
        public long timestamp;

        public ChatMessage(String type, String username, String content) {
            this.type = type;
            this.username = username;
            this.content = content;
            this.timestamp = System.currentTimeMillis();
        }
    }

    public interface ChatCallback {
        void onMessage(ChatMessage message);
        void onUserJoined(String username);
        void onUserLeft(String username);
        void onConnectionStatus(boolean connected);
    }

    private ChatCallback callback;

    public ChatWebSocket(Context context) {
        this.context = context;
        this.client = new OkHttpClient.Builder()
            .readTimeout(0, TimeUnit.MILLISECONDS)
            .build();
    }

    public void setCallback(ChatCallback callback) {
        this.callback = callback;
    }

    // Connect to chat server
    public void connect(String serverUrl, final String username) {
        Request request = new Request.Builder()
            .url(serverUrl)
            .build();

        WebSocketListener listener = new WebSocketListener() {
            @Override
            public void onOpen(WebSocket webSocket, Response response) {
                System.out.println("Chat Connected as: " + username);
                if (callback != null) {
                    callback.onConnectionStatus(true);
                }

                // Send join message
                ChatMessage joinMessage = new ChatMessage("join", username, "");
                webSocket.send(toJson(joinMessage));
            }

            @Override
            public void onMessage(WebSocket webSocket, String text) {
                ChatMessage message = fromJson(text);
                if (message != null && callback != null) {
                    switch (message.type) {
                        case "join":
                            callback.onUserJoined(message.username);
                            break;
                        case "leave":
                            callback.onUserLeft(message.username);
                            break;
                        case "message":
                            callback.onMessage(message);
                            break;
                    }
                }
            }

            @Override
            public void onClosed(WebSocket webSocket, int code, String reason) {
                System.out.println("Chat Closed");
                if (callback != null) {
                    callback.onConnectionStatus(false);
                }
            }

            @Override
            public void onFailure(WebSocket webSocket, Throwable t, Response response) {
                System.out.println("Chat Error: " + t.getMessage());
                if (callback != null) {
                    callback.onConnectionStatus(false);
                }
            }
        };

        webSocket = client.newWebSocket(request, listener);
    }

    // Send chat message
    public void sendMessage(String username, String content) {
        ChatMessage message = new ChatMessage("message", username, content);
        if (webSocket != null) {
            webSocket.send(toJson(message));
        }
    }

    // Leave chat
    public void leave(String username) {
        ChatMessage leaveMessage = new ChatMessage("leave", username, "");
        if (webSocket != null) {
            webSocket.send(toJson(leaveMessage));
            webSocket.close(1000, "User leaving");
            webSocket = null;
        }
    }

    private String toJson(ChatMessage message) {
        try {
            JSONObject json = new JSONObject();
            json.put("type", message.type);
            json.put("username", message.username);
            json.put("content", message.content);
            json.put("timestamp", message.timestamp);
            return json.toString();
        } catch (Exception e) {
            return "{}";
        }
    }

    private ChatMessage fromJson(String json) {
        try {
            JSONObject obj = new JSONObject(json);
            ChatMessage message = new ChatMessage(
                obj.optString("type"),
                obj.optString("username"),
                obj.optString("content")
            );
            message.timestamp = obj.optLong("timestamp", System.currentTimeMillis());
            return message;
        } catch (Exception e) {
            return null;
        }
    }
}

// 4. WebSocket Heartbeat/Ping
public class HeartbeatWebSocket {
    private Context context;
    private OkHttpClient client;
    private WebSocket webSocket;
    private Runnable heartbeatRunnable;
    private Handler heartbeatHandler;

    public HeartbeatWebSocket(Context context, String url) {
        this.context = context;
        this.client = new OkHttpClient.Builder()
            .pingInterval(30, TimeUnit.SECONDS) // Send ping every 30 seconds
            .build();
        this.heartbeatHandler = new Handler(Looper.getMainLooper());
    }

    // Connect with heartbeat
    public void connect(String url) {
        Request request = new Request.Builder()
            .url(url)
            .build();

        WebSocketListener listener = new WebSocketListener() {
            @Override
            public void onOpen(WebSocket webSocket, Response response) {
                System.out.println("Heartbeat WebSocket Connected");
                startHeartbeat(webSocket);
            }

            @Override
            public void onMessage(WebSocket webSocket, String text) {
                System.out.println("Received: " + text);
            }

            @Override
            public void onClosing(WebSocket webSocket, int code, String reason) {
                stopHeartbeat();
            }

            @Override
            public void onClosed(WebSocket webSocket, int code, String reason) {
                stopHeartbeat();
            }

            @Override
            public void onFailure(WebSocket webSocket, Throwable t, Response response) {
                stopHeartbeat();
            }
        };

        webSocket = client.newWebSocket(request, listener);
    }

    // Start heartbeat
    private void startHeartbeat(final WebSocket ws) {
        heartbeatRunnable = new Runnable() {
            @Override
            public void run() {
                try {
                    JSONObject heartbeat = new JSONObject();
                    heartbeat.put("type", "heartbeat");
                    heartbeat.put("timestamp", System.currentTimeMillis());
                    ws.send(heartbeat.toString());
                    System.out.println("Heartbeat sent");

                    // Schedule next heartbeat
                    heartbeatHandler.postDelayed(this, 15000); // 15 seconds
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        heartbeatHandler.postDelayed(heartbeatRunnable, 15000); // Start after 15 seconds
    }

    // Stop heartbeat
    private void stopHeartbeat() {
        if (heartbeatRunnable != null) {
            heartbeatHandler.removeCallbacks(heartbeatRunnable);
            heartbeatRunnable = null;
        }
    }

    // Close connection
    public void close() {
        stopHeartbeat();
        if (webSocket != null) {
            webSocket.close(1000, "Closing");
            webSocket = null;
        }
    }
}

// 5. WebSocket Manager (Singleton)
public class WebSocketManager {
    private static volatile WebSocketManager instance;
    private Context context;
    private java.util.Map<String, WebSocket> connections = new java.util.HashMap<>();

    public static class WebSocketConfig {
        public String url;
        public String key;
        public boolean autoReconnect = true;
        public long reconnectDelay = 3000;

        public WebSocketConfig(String url) {
            this.url = url;
            this.key = url;
        }

        public WebSocketConfig(String url, String key) {
            this.url = url;
            this.key = key;
        }
    }

    private WebSocketManager(Context context) {
        this.context = context.getApplicationContext();
    }

    public static WebSocketManager getInstance(Context context) {
        if (instance == null) {
            synchronized (WebSocketManager.class) {
                if (instance == null) {
                    instance = new WebSocketManager(context);
                }
            }
        }
        return instance;
    }

    // Connect with config
    public void connect(WebSocketConfig config, WebSocketListener listener) {
        OkHttpClient client = new OkHttpClient.Builder()
            .readTimeout(0, TimeUnit.MILLISECONDS)
            .build();

        Request request = new Request.Builder()
            .url(config.url)
            .build();

        WebSocket ws = client.newWebSocket(request, listener);
        connections.put(config.key, ws);
    }

    // Send message
    public void send(String key, String message) {
        WebSocket ws = connections.get(key);
        if (ws != null) {
            ws.send(message);
        }
    }

    // Close specific connection
    public void close(String key) {
        WebSocket ws = connections.get(key);
        if (ws != null) {
            ws.close(1000, "Closing");
            connections.remove(key);
        }
    }

    // Close all connections
    public void closeAll() {
        for (WebSocket ws : connections.values()) {
            ws.close(1000, "Closing all");
        }
        connections.clear();
    }
}

// Main demonstration
public class WebSocketDemo {
    public static void demonstrateWebSocket(Context context) {
        System.out.println("=== Android Java WebSocket Examples ===\n");

        // 1. Basic WebSocket
        System.out.println("--- 1. Basic WebSocket ---");
        BasicWebSocketExample basicWs = new BasicWebSocketExample(context);
        // basicWs.connect("wss://echo.websocket.org");
        // basicWs.sendMessage("Hello WebSocket!");

        // 2. Advanced WebSocket with reconnection
        System.out.println("\n--- 2. Advanced WebSocket with Reconnection ---");
        AdvancedWebSocketExample advancedWs = new AdvancedWebSocketExample(context, "wss://echo.websocket.org");
        // advancedWs.setCallback(new AdvancedWebSocketExample.WebSocketCallback() {
        //     @Override
        //     public void onConnected() {
        //         System.out.println("Connected!");
        //     }
        //
        //     @Override
        //     public void onMessage(String text) {
        //         System.out.println("Message: " + text);
        //     }
        //
        //     @Override
        //     public void onMessage(ByteString bytes) {
        //         System.out.println("Bytes received");
        //     }
        //
        //     @Override
        //     public void onDisconnected() {
        //         System.out.println("Disconnected");
        //     }
        //
        //     @Override
        //     public void onError(String error) {
        //         System.out.println("Error: " + error);
        //     }
        // });
        // advancedWs.connect("wss://echo.websocket.org");

        // 3. Chat WebSocket
        System.out.println("\n--- 3. Chat WebSocket ---");
        ChatWebSocket chatWs = new ChatWebSocket(context);
        // chatWs.setCallback(new ChatWebSocket.ChatCallback() {
        //     @Override
        //     public void onMessage(ChatMessage message) {
        //         System.out.println("Chat message from " + message.username + ": " + message.content);
        //     }
        //
        //     @Override
        //     public void onUserJoined(String username) {
        //         System.out.println(username + " joined the chat");
        //     }
        //
        //     @Override
        //     public void onUserLeft(String username) {
        //         System.out.println(username + " left the chat");
        //     }
        //
        //     @Override
        //     public void onConnectionStatus(boolean connected) {
        //         System.out.println("Connection status: " + (connected ? "Connected" : "Disconnected"));
        //     }
        // });
        // chatWs.connect("wss://chat.example.com", "User123");
        // chatWs.sendMessage("User123", "Hello everyone!");

        // 4. WebSocket Manager
        System.out.println("\n--- 4. WebSocket Manager ---");
        WebSocketManager wsManager = WebSocketManager.getInstance(context);
        // wsManager.connect(
        //     new WebSocketManager.WebSocketConfig("wss://echo.websocket.org"),
        //     listener
        // );

        System.out.println("\n=== All WebSocket Examples Completed ===");
    }
}