Android/Retrofit:应用程序不通过 h​​ttp 进行通信,仅通过 https 进行通信

use*_*379 1 https android http retrofit

我正在尝试创建一个通过 http 协议与服务器通信的 Android 应用程序。我正在使用 Retrofit 向服务器发送 GET 请求,但总是收到以下错误:

java.net.UnknownServiceException: CLEARTEXT communication to http://demo5373349.mockable.io/ not permitted by network security policy
Run Code Online (Sandbox Code Playgroud)

虽然尝试通过 https 访问服务器时不存在此类问题,但我也会编写服务器端,并且我应该使用 http。

这是代码:

private TextView textView;
private EditText editText;
private Button getButton;
private Retrofit retrofit;
private ServerConnection connection;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    retrofit = new Retrofit.Builder()
            .baseUrl("http://demo5373349.mockable.io/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    connection = retrofit.create(ServerConnection.class);

    textView = findViewById(R.id.textView);
    editText = findViewById(R.id.editText);
    getButton = findViewById(R.id.buttonGET);
    getButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            getHandler();
        }
    });

}

private void getHandler(){
    connection.sendGET().enqueue(new Callback<Message>() {
        @Override
        public void onResponse(Call<Message> call, Response<Message> response) {
            if(response.isSuccessful()) {
                textView.setText(response.body().toString());
            }else {
                textView.setText("Server Error");
            }
        }

        @Override
        public void onFailure(Call<Message> call, Throwable t) {
            textView.setText("Connection Error");
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

和界面:

public interface ServerConnection {
    @GET("./")
    Call<Message> sendGET();
}
Run Code Online (Sandbox Code Playgroud)

Bre*_*ley 5

从 Android 9.0 (SDK 28) 开始,默认情况下禁用明文网络通信。请参阅Android 9.0 (SDK 28) 禁用明文

您有多种选择,按安全偏好的顺序排列:

  • 将所有网络访问更改为使用 HTTPS。
  • 将网络安全配置文件添加到您的项目中。
  • android:usesCleartextTraffic="true"通过添加到清单中的应用程序来启用对应用程序的明文支持。

要将网络安全文件添加到您的项目中,您需要做两件事。您需要将文件规范添加到清单中:

<application android:networkSecurityConfig="@xml/network_security_config" .../>
Run Code Online (Sandbox Code Playgroud)

其次,创建文件 res/xml/network_security_config.xml 并指定您的安全需求:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">insecure.example.com</domain>
    </domain-config>
</network-security-config>
Run Code Online (Sandbox Code Playgroud)