LINUX.ORG.RU

Помогите отправить HTTP post запрос через curl (консоль linux)

 ,


0

1

Здравствуйте. На java отправлял так:


public class Main {

/** Confidential Server API key gotten from the Google Dev Console ->
   * Credentials -> Public API Access -> Key for Android Apps */
  final static String AUTH_KEY = "AIzaSyXXXXXXXXXXXXXXXXXXXXXX";    // set in a static initializer, not shown
   
  final static String POST_URL = "https://android.googleapis.com/gcm/send";
       
  public static void main(String[] args) throws Exception {

      final String[][]  MESSAGE_HEADERS = {
          {"Content-Type", "application/json"},
          { "Authorization", "key=" + AUTH_KEY}
      };

      String regIdFromClientApp = "APA91bHmt4N2vRurDrsYE-zDXLKg6tVw0gZBFQRtFxp06qfVUTfJ5_dflUlVL-8Ud4nK2IwGt-oyKsTJANrQznlSmFUY21g4v5eZcRpANSTf1Mn5jWpSdNXrVz25TrjfHZvqefbF6UQbpQl17aKm6edMVLOnyCVy-w"; // has to be set somehow!
      String jsonMessage = 
              "{\n" +
              "    \"registration_ids\" : [\""+ regIdFromClientApp + "\"],\n" +
              "    \"data\" : {\n" +
              "        \"m\": \"See your доктор ASAP!\"\n" +
              "    }\n" +
              "}\n";
       
      // Dump out the HTTP send for debugging
      for (String[] hed : MESSAGE_HEADERS) {
          System.out.println(hed[0] + "=>" + hed[1]);
      }
      System.out.println(jsonMessage);
       
      // Actually send it.
      sendMessage(POST_URL, MESSAGE_HEADERS, jsonMessage);
  }

  private static void sendMessage(String postUrl, String[][] messageHeaders, String jsonMessage) throws IOException {
      HttpURLConnection conn = (HttpURLConnection) new URL(postUrl).openConnection();
      
      for (String[] h : messageHeaders) {
          conn.setRequestProperty(h[0], h[1]);
      }
      
      System.out.println("Connected to " + postUrl);
      
      conn.setDoOutput(true);
      conn.setDoInput(true);
      conn.setUseCaches(false);       // ensure response always from server

      PrintWriter pw = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF8"));
       
      pw.print(jsonMessage);
      pw.close();
       
      System.out.println("Connection status code " + conn.getResponseCode());
  }
}

На PHP так:

<?php
function sendPushNotificationToGCM($registatoin_ids, $message) {
    //Google cloud messaging GCM-API url
        $url = 'https://android.googleapis.com/gcm/send';
        $fields = array(
            'registration_ids' => $registatoin_ids,
            'data' => $message,
        );
    // Google Cloud Messaging GCM API Key
    define("GOOGLE_API_KEY", "AIzaSyBzFcuWKSXXXXXXXXXXXXX");    
        $headers = array(
            'Authorization: key=' . GOOGLE_API_KEY,
            'Content-Type: application/json'
        );
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0); 
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
        $result = curl_exec($ch);       
        if ($result === FALSE) {
            die('Curl failed: ' . curl_error($ch));
        }
        curl_close($ch);
        return $result;
    }
	
?>
...

Спустя ~год снова пытаюсь разобраться, только теперь через curl и консоль linux.



Последнее исправление: astrgan (всего исправлений: 1)

Вы не можете добавлять комментарии в эту тему. Тема перемещена в архив.