You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Android Java应用中Proxy与ProxySelector使用及代理防滥用问询

Android Proxy Implementation & Protecting Paid Proxy Resources

Hey there! As someone who’s built Android apps with proxy requirements before, let’s tackle your two questions one by one in a practical, actionable way.


1. Using Proxy and ProxySelector in Android Java Code

These classes help route your app’s network traffic through a proxy, but their usage depends on whether you need proxy for specific requests or all app traffic.

For individual requests (e.g., OkHttp or URLConnection)

If you only want certain API calls to use the proxy, directly instantiate a Proxy object and attach it to your network client:

Example with OkHttp (most common for Android):

// Create a Proxy instance (adjust type, host, and port to match your proxy)
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("your-proxy-host", 8080));

// Add proxy authentication if required
Authenticator proxyAuth = new Authenticator() {
    @Override
    public Request authenticate(Route route, Response response) throws IOException {
        String credentials = Credentials.basic("proxy-username", "proxy-password");
        return response.request().newBuilder()
                .header("Proxy-Authorization", credentials)
                .build();
    }
};

// Build your OkHttpClient with proxy settings
OkHttpClient client = new OkHttpClient.Builder()
        .proxy(proxy)
        .proxyAuthenticator(proxyAuth)
        .build();

// Use this client for your proxy-enabled requests
Request request = new Request.Builder()
        .url("https://your-target-api.com/data")
        .build();

try (Response response = client.newCall(request).execute()) {
    // Handle your response here
} catch (IOException e) {
    e.printStackTrace();
}

Example with native HttpURLConnection:

URL targetUrl = new URL("https://your-target-api.com/data");
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("your-proxy-host", 8080));
HttpURLConnection connection = (HttpURLConnection) targetUrl.openConnection(proxy);

// Add proxy auth if needed
String authString = "proxy-username:proxy-password";
String encodedAuth = "Basic " + Base64.encodeToString(authString.getBytes(), Base64.NO_WRAP);
connection.setRequestProperty("Proxy-Authorization", encodedAuth);

// Proceed with connecting and reading the response
connection.connect();

For global proxy rules with ProxySelector

If you want to automatically apply proxy settings based on the target URL (e.g., only route specific domains through proxy), use ProxySelector:

ProxySelector customSelector = new ProxySelector() {
    @Override
    public List<Proxy> select(URI uri) {
        List<Proxy> proxies = new ArrayList<>();
        // Apply proxy only for specific domains
        if (uri.getHost().endsWith("your-target-domain.com")) {
            proxies.add(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("your-proxy-host", 8080)));
        } else {
            // Use direct connection for all other requests
            proxies.add(Proxy.NO_PROXY);
        }
        return proxies;
    }

    @Override
    public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
        // Log or handle proxy connection failures
        Log.e("ProxyError", "Failed to connect to proxy for URI: " + uri, ioe);
    }
};

// Set this selector as the global default (affects all network libraries using default settings)
ProxySelector.setDefault(customSelector);

2. Preventing Users from Viewing/Abusing Paid Proxies

Protecting paid proxy resources requires a mix of client-side security and backend controls—here’s what works:

  • Never store proxy details in plain text: Avoid hardcoding proxy host, username, or password in your code. Use Android’s EncryptedSharedPreferences to encrypt and store these values, making them far harder to extract even on rooted devices.
  • Use a backend relay: Don’t let your app connect directly to the paid proxy. Instead, have your app send requests to your own backend server. Your backend will then forward the request through the paid proxy, process the response, and send it back to the app. This way, users never interact with the paid proxy directly.
  • Add request validation: On your backend, require authenticated requests (e.g., using user-specific tokens) before forwarding traffic through the proxy. You can also limit request frequency per user to prevent bulk abuse.
  • Restrict proxy scope: Configure your paid proxy to only allow access to the exact domains/IPs your app needs. Even if proxy details leak, attackers can’t use it for unrelated traffic.
  • Obfuscate your code: Enable R8 code obfuscation in Android Studio to scramble proxy-related logic. This makes it much harder for reverse-engineers to find or extract proxy credentials.
  • Monitor usage: Regularly check your paid proxy’s access logs. Flag unusual activity (e.g., repeated requests to non-target domains, excessive traffic from a single IP) and block abusive users or IPs immediately.

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

火山引擎 最新活动