【问题标题】:java.net.SocketException: Connection reset only in android 9java.net.SocketException:仅在 android 9 中重置连接
【发布时间】:2019-05-08 09:33:37
【问题描述】:

我在尝试发送 GET 请求时收到 java.net.SocketException: Connection reset。问题是我使用的相同代码在 Android 8 和更低版本中运行良好,但在 Android 9 中不起作用。此外,此问题仅发生在我的应用程序中的某些请求上,而不是全部。此库用于 HTTP 请求:https://github.com/kevinsawicki/http-request

我已经将android:usesCleartextTraffic="true" 添加到清单中,但它没有帮助。

这是我用来发送请求的一些代码:

    String response = "";

    args.put("InvokationTarget", methodName);
    args.put("DepartmentId", String.valueOf(departmentId));

    try {
        if (mWebServiceUrl != null) {
            HttpRequest request = HttpRequest.get(mWebServiceUrl, args, true);

            Log.i(TAG, "Request: " + request.toString());
            long ts = System.currentTimeMillis();

            if (request.ok()) {
                response = request.body(HttpRequest.CHARSET_UTF8);

                long delta = System.currentTimeMillis() - ts;
                Log.i(TAG, "Response: " + response);
                Log.i(TAG, "Duration: " + (delta / 1000.0) + " sec.");
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "Error: " + e.getMessage(), e);
        ACRA.getErrorReporter().handleException(e);
        response = e.getMessage();
    }

【问题讨论】:

    标签: java android android-9.0-pie


    【解决方案1】:

    您需要添加networkSecurityConfig

    <?xml version="1.0" encoding="utf-8"?>
    <manifest ... >
        <application android:networkSecurityConfig="@xml/network_security_config"
                        ... >
            ...
        </application>
    </manifest>
    

    network_security_config.xml

    <?xml version="1.0" encoding="utf-8"?>
    <network-security-config>
        <domain-config>
            <domain includeSubdomains="true">example.com</domain>
            <trust-anchors>
                <certificates src="@raw/my_ca"/>
            </trust-anchors>
        </domain-config>
    </network-security-config>
    

    【讨论】:

    • 现在没有例外,谢谢。但是方法调用后什么也没有发生,我无法收到响应
    猜你喜欢
    • 2016-09-19
    • 2010-09-08
    • 2021-03-10
    • 1970-01-01
    相关资源
    最近更新 更多