Android /翻新版:应用程序无法通过http通信,只能通过https

时间:2018-08-24 12:37:24

标签: android http https retrofit

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

java.net.UnknownServiceException: CLEARTEXT communication to http://demo5373349.mockable.io/ not permitted by network security policy

虽然尝试通过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");
        }
    });
}

和界面:

public interface ServerConnection {
    @GET("./")
    Call<Message> sendGET();
}

1 个答案:

答案 0 :(得分:1)

从Android 9.0(SDK 28)开始,默认情况下使用明文网络通信处于禁用状态。参见Android 9.0 (SDK 28) cleartext disabled

按照安全性偏好设置,您有几种选择:

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

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

<application android:networkSecurityConfig="@xml/network_security_config" .../>

第二,创建文件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>