---
# System prepended metadata

title: '`Cleartext HTTP traffic to 192.168.1.161 not permitted` error'
tags: [系統環境]

---

`Cleartext HTTP traffic to 192.168.1.161 not permitted` error
===

### 原因
在實作 **HttpURlConnection** 時，執行 `DataOutputStream` 發生跳出例外 **`Cleartext HTTP traffic to 192.168.1.161 not permitted`**
```java=
URL url = new URL(apiUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

...
    
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
```

### Solution

#### 靜態: 只允許定義的 domain (192.168.1.161)

參考 [Option 2](https://stackoverflow.com/a/50834600) 的解法

EX：填入 server domain `192.168.1.161`，不須加上 port 否則依然會 error

- create `network_security_config.xml` under `res/xml/`
```xml=
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">192.168.1.161</domain>
    </domain-config>
</network-security-config>
```

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

#### 動態: 可允許不同 domain

[參考](https://stackoverflow.com/a/51902630)

```xml=
<application
    ...
    android:usesCleartextTraffic="true">
    ...
</application>

```

## Ref.
[Android 8: Cleartext HTTP traffic not permitted](https://stackoverflow.com/a/50834600)

###### tags: `系統環境`