You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求与Python HTTP流读取代码等价的Java(含Android)实现方案

Equivalent Java/Android Implementations for HTTP Stream Reading (Matching Your Python Code)

I get it—finding the right way to read HTTP streams in Java/Android can be tricky when most resources focus on server-side streams or file uploads. Let's break down the equivalent synchronous and asynchronous implementations that match your Python requests and aiohttp code.

Key Background

Your Python code reads a chunked HTTP stream line-by-line, which is common for things like Server-Sent Events (SSE) or continuous data feeds. In Java, we'll use libraries that handle streaming responses properly without buffering the entire payload.


1. Synchronous Implementation (Matching sync_listen())

Option 1: Java 11+ Standard HttpClient

Java 11 introduced a modern HttpClient that supports streaming natively:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class SyncStreamReader {
    private static final String LISTEN_URL = "https://somehttpstreamingurl";
    private static final String USER_AGENT = "stream client";

    public static void syncListen() throws IOException, InterruptedException {
        HttpClient client = HttpClient.newHttpClient();
        
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(LISTEN_URL))
                .header("User-Agent", USER_AGENT)
                .build();

        // Send request with a streaming body handler
        HttpResponse<InputStreamReader> response = client.send(
                request,
                HttpResponse.BodyHandlers.ofInputStreamReader()
        );

        // Read line-by-line from the stream
        try (BufferedReader reader = new BufferedReader(response.body())) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (!line.isEmpty()) {
                    System.out.println(line);
                }
            }
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        syncListen();
    }
}

Option 2: OkHttp (Great for Android & Cross-Platform)

OkHttp is widely used in Android and handles streaming seamlessly:

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class OkHttpSyncStreamReader {
    private static final String LISTEN_URL = "https://somehttpstreamingurl";
    private static final String USER_AGENT = "stream client";

    public static void syncListen() throws IOException {
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(LISTEN_URL)
                .header("User-Agent", USER_AGENT)
                .build();

        try (Response response = client.newCall(request).execute()) {
            ResponseBody body = response.body();
            if (body == null) {
                return;
            }

            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(body.byteStream()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    if (!line.isEmpty()) {
                        System.out.println(line);
                    }
                }
            }
        }
    }

    public static void main(String[] args) throws IOException {
        syncListen();
    }
}

2. Asynchronous Implementation (Matching async_listen())

Option 1: Java 11+ Standard HttpClient Async

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.CompletableFuture;

public class AsyncStreamReader {
    private static final String LISTEN_URL = "https://somehttpstreamingurl";
    private static final String USER_AGENT = "stream client";

    public static void asyncListen() {
        HttpClient client = HttpClient.newHttpClient();
        
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(LISTEN_URL))
                .header("User-Agent", USER_AGENT)
                .build();

        // Send async request with streaming handler
        CompletableFuture<Void> future = client.sendAsync(
                request,
                HttpResponse.BodyHandlers.ofInputStreamReader()
        ).thenAccept(response -> {
            try (BufferedReader reader = new BufferedReader(response.body())) {
                String line;
                while ((line = reader.readLine()) != null) {
                    if (!line.isEmpty()) {
                        System.out.println(line);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

        // Wait for completion (optional, depending on your use case)
        future.join();
    }

    public static void main(String[] args) {
        asyncListen();
    }
}

Option 2: OkHttp Async (Android-Friendly)

For Android, never run network operations on the main thread, so OkHttp's async callback is perfect:

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class OkHttpAsyncStreamReader {
    private static final String LISTEN_URL = "https://somehttpstreamingurl";
    private static final String USER_AGENT = "stream client";

    public static void asyncListen() {
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(LISTEN_URL)
                .header("User-Agent", USER_AGENT)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try (ResponseBody body = response.body()) {
                    if (body == null) {
                        return;
                    }

                    try (BufferedReader reader = new BufferedReader(
                            new InputStreamReader(body.byteStream()))) {
                        String line;
                        while ((line = reader.readLine()) != null) {
                            if (!line.isEmpty()) {
                                // Note: In Android, update UI on main thread if needed
                                // runOnUiThread(() -> { /* update UI */ });
                                System.out.println(line);
                            }
                        }
                    }
                }
            }
        });
    }

    public static void main(String[] args) {
        asyncListen();
        // Keep the program running (for demo purposes)
        try {
            Thread.sleep(Long.MAX_VALUE);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Android-Specific Notes

  1. Network Permission: Add this to your AndroidManifest.xml:
    <uses-permission android:name="android.permission.INTERNET" />
    
  2. Main Thread Restriction: All network operations (sync or async) must run on a background thread. For async OkHttp, the onResponse callback runs on a background thread—use runOnUiThread or a CoroutineScope if you need to update the UI.
  3. Dependency for OkHttp: Add to your build.gradle (Module level):
    implementation 'com.squareup.okhttp3:okhttp:4.12.0'
    

内容的提问来源于stack exchange,提问作者TMJnoob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:29:05