Send message by OneSignal from Android

0

The code below serves to send a push message via OneSignal, while running on NetBeans everything works perfectly but when trying to run on android I did not succeed. I would like you to help me, then follow the codes:

This code that works on NetBeans: package javaapplication2;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;


public class JavaApplication2 {


    public static void main(String[] args) {

    String titulo = "Esse é um bom título";
    String mensagem = "Uma excelente mensagem para você";

        enviarNotificacao(titulo, mensagem);
    }

    public static void enviarNotificacao(String mTitle, String mMensagem ){

   try {
   String jsonResponse;

   URL url = new URL("https://onesignal.com/api/v1/notifications");
   HttpURLConnection con = (HttpURLConnection)url.openConnection();
   con.setUseCaches(false);
   con.setDoOutput(true);
   con.setDoInput(true);

   con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
   con.setRequestProperty("Authorization", "Basic ZGJjMzI3ZmMtYzFlMy00YTRjLWEyOTctYTY4YTUyNTE1MTY1");
   con.setRequestMethod("POST");

   String strJsonBody = "{"
                      +   "\"app_id\": \"08603795-b086-4d1e-9030-122d4270c398\","
                      +   "\"included_segments\": [\"All\"],"
                      +   "\"data\": {\"foo\": \"bar\"},"

                      +   "\"headings\": {\"en\": \""+ mTitle +"\"},"
                      +   "\"contents\": {\"en\": \""+ mMensagem + "\"}"
                      + "}";


   System.out.println("strJsonBody:\n" + strJsonBody);

   byte[] sendBytes = strJsonBody.getBytes("UTF-8");
   con.setFixedLengthStreamingMode(sendBytes.length);

   OutputStream outputStream = con.getOutputStream();
   outputStream.write(sendBytes);

   int httpResponse = con.getResponseCode();
   System.out.println("httpResponse: " + httpResponse);

   if (  httpResponse >= HttpURLConnection.HTTP_OK
      && httpResponse < HttpURLConnection.HTTP_BAD_REQUEST) {
      Scanner scanner = new Scanner(con.getInputStream(), "UTF-8");
      jsonResponse = scanner.useDelimiter("\A").hasNext() ? scanner.next() : "";
      scanner.close();
   }
   else {
      Scanner scanner = new Scanner(con.getErrorStream(), "UTF-8");
      jsonResponse = scanner.useDelimiter("\A").hasNext() ? scanner.next() : "";
      scanner.close();
   }
   System.out.println("jsonResponse:\n" + jsonResponse);

} catch(Throwable t) {
   t.printStackTrace();
}
    }


}

This code is my attempt on android:

import android.os.StrictMode;
import android.util.Log;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Scanner;

public class Notifications {

private String jsonResponse;

public void setNotification(String titulo, String mensagem) {

    int SDK_INT = android.os.Build.VERSION.SDK_INT;
    if (SDK_INT > 8) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
        //your codes here

        URL url = null;
        try {
            url = new URL("https://onesignal.com/api/v1/Notifications");
        } catch (MalformedURLException e) {
            e.printStackTrace();
            Log.i("Erro na notificacao", "Erro ao enviar 1");
        }
        HttpURLConnection con = null;
        try {
            con = (HttpURLConnection) url.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
            Log.i("Erro na notificacao", "Erro ao enviar 2");
        }
        con.setUseCaches(false);
        con.setDoOutput(true);
        con.setDoInput(true);

        con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        con.setRequestProperty("Authorization", "Basic ZGJjMzI3ZmMtYzFlMy00YTRjLWEyOTctYTY4YTUyNTE1MTY1");
        try {
            con.setRequestMethod("POST");
        } catch (ProtocolException e) {
            e.printStackTrace();
            Log.i("Erro na notificacao", "Erro ao enviar 3");
        }

        String strJsonBody = "{"
                + "\"app_id\": \"08603795-b086-4d1e-9030-122d4270c398\","
                + "\"included_segments\": [\"All\"],"
                + "\"data\": {\"foo\": \"bar\"},"
                + "\"headings\": {\"en\": \"" + titulo + "\"},"
                + "\"contents\": {\"en\": \"" + mensagem + "\"}"
                + "}";


        System.out.println("strJsonBody:\n" + strJsonBody);

        byte[] sendBytes = new byte[0];
        try {
            sendBytes = strJsonBody.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            Log.i("Erro na notificacao", "Erro ao enviar 4");
        }
        con.setFixedLengthStreamingMode(sendBytes.length);

        OutputStream outputStream = null;
        try {
            outputStream = con.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
            Log.i("Erro na notificacao", "Erro ao enviar 5");
        }
        try {
            outputStream.write(sendBytes);
        } catch (IOException e) {
            e.printStackTrace();
            Log.i("Erro na notificacao", "Erro ao enviar 6");
        }

        int httpResponse = 0;
        try {
            httpResponse = con.getResponseCode();
        } catch (IOException e) {
            e.printStackTrace();
            Log.i("Erro na notificacao", "Erro ao enviar 7");
        }
        System.out.println("httpResponse: " + httpResponse);

        System.out.println("jsonResponse:\n" + jsonResponse);

    }
}
}
    
asked by anonymous 16.06.2018 / 04:31

0 answers