-2

I'm using that code to send POST requests.

Now i need to add header to this, any ways of doing it? In Google most ways is to use another methods, like HttpPost and addHeader method.

try {
        System.out.println("FirebaseInstanceId.getInstance().getToken()" + token);

        //String data = URLEncoder.encode("?api-fcm=register", "UTF-8");

        String data = URLEncoder.encode("regid", "UTF-8")
                + "=" + URLEncoder.encode(FirebaseInstanceId.getInstance().getToken(), "UTF-8");

        if ( ContextCompat.checkSelfPermission( this, Manifest.permission.READ_PHONE_STATE ) == PackageManager.PERMISSION_GRANTED ) {
            data += "&" + URLEncoder.encode("serial", "UTF-8") + "=" + URLEncoder.encode( Build.SERIAL, "UTF-8");
        }

        data += "&" + URLEncoder.encode("device_name", "UTF-8")
                + "=" + URLEncoder.encode(getDeviceName(), "UTF-8");


        data += "&" + URLEncoder.encode("os_version", "UTF-8")
                + "=" + URLEncoder.encode(getAndroidVersion(), "UTF-8");

        String text = "";
        BufferedReader reader = null;

        try {
            URL url = new URL("http://somelink");

            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();

            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = null;

            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            text = sb.toString();
        } catch (Exception ex) {
Vadim
  • 335
  • 3
  • 14
  • did you tried google for it? there are already plenty similar questions here on StackOverflow – Selvin Dec 01 '17 at 12:29

1 Answers1

2

Do code like this:

  HttpUrlConnection myURLConnection = (HttpUrlConnection)conn;
  myURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  myURLConnection.setRequestProperty("Content-Length", "" + postData.getBytes().length);
  myURLConnection.setRequestProperty("Content-Language", "en-US");

add this after line:

  URLConnection conn = url.openConnection();

and here "Content-Type", "Content-Length", "Content-Language" are headers here.

Thanks and let me know if need more.

happy Coding!!

Ankit Patidar
  • 2,731
  • 1
  • 14
  • 22