LoginSignup
0
0

More than 3 years have passed since last update.

使用したクーポンコードを指定したエンドポイントにポストバックする

Posted at

広告の成果計測等のために、使用されたクーポンコード等の情報を含めて計測システムのエンドポイントへポストバックする必要がある際の成果通知の仕方です。

今回はHttpURLConnectionを利用しました。

security configの設定とmanifestの設定

設定するポストバック先のURLがhttps://〜であればこの設定は不要です。
Android 9(Pie)では暗号化されていない通信はできない、つまりhttp://ではじまるURLへの通信はデフォルトでは不可能です。
※設定するURLがhttps://で始まればこの手順は必要ありません。

security config設定

app/xmlディレクトリに以下のファイルを作成します。

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>

指定したドメインに暗号化されていない通信(http://)を許可(cleartextTrafficPremittedをtrue)しています。

manifestの設定

その後AndroidManifestのapplicationタグの属性部分に

android:networkSecurityConfig="@xml/network_security_config

を追加します。
(例)

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">

ポストバック

ポストバックを発生させたいイベント等が発生したときに以下のメソッドを実行します。
クーポンコード等、イベント毎に変わる可能性があるユーザ入力値は引数として受け取る設定をしています。

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)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0