This is a method of notifying the results when it is necessary to post back to the endpoint of the measurement system including the information such as the coupon code used for measuring the results of the advertisement.
This time I used HttpURLConnection.
If the postback destination URL to be set is https: // ~, this setting is not necessary. Android 9 (Pie) does not allow unencrypted communication, that is, communication to URLs starting with http: // is not possible by default.
Create the following files in the app / xml directory.
network_security_config.xml
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">XXXX.net</domain>
</domain-config>
</network-security-config>
Allows unencrypted communication (http: //) to the specified domain (cleartextTrafficPremitted true).
After that, in the attribute part of the application tag of Android Manifest
android:networkSecurityConfig="@xml/network_security_config
To add. (Example)
AndroidManifest.xml
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:networkSecurityConfig="@xml/network_security_config">
Execute the following method when an event etc. that you want to generate a postback occurs. User input values that may change for each event, such as coupon codes, are set to be received as arguments.
Activity.java
public void postBack(final String cp){
new Thread(new Runnable() {
@Override
public void run() {
try{
URL url = new URL("https:/XXXX.net?coupon="+cp);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
String str = InputStreamToString(con.getInputStream());
Log.d("HTTP",str);
}catch(Exception e){
System.out.println(e);
}
}
}).start();
}
static String InputStreamToString(InputStream is) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while( (line=br.readLine()) != null ){
sb.append(line);
}
br.close();
return sb.toString();
}
HttpURLConnection (Java Platform SE 8)
Recommended Posts