IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

C# Discussion :

Comment Envoyer des données à l'aide de la classe de WebRequest [Débutant]


Sujet :

C#

  1. #1
    Membre éprouvé Avatar de shaun_the_sheep
    Homme Profil pro
    Chef de projet NTIC
    Inscrit en
    Octobre 2004
    Messages
    1 619
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Chef de projet NTIC
    Secteur : Enseignement

    Informations forums :
    Inscription : Octobre 2004
    Messages : 1 619
    Points : 996
    Points
    996
    Par défaut Comment Envoyer des données à l'aide de la classe de WebRequest
    Bonsoir,

    je réalise un flux en C# qui a pour objectif d'envoyer des fichiers vers BlackBoard. (LMS)

    le formateur m'a enseigné une méthode simple utilisant CURL comme ceci

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    curl -k -w %%{http_code} -H "Content-Type:text/plain" -u login:password --data-binary @fichierBB.csv https://URL_BLACKBOARD > logBB.txt
    j'aimerai me dispenser de CURL et le faire directement en c# , je me suis un peu renseigné sur la méthode WebRequest mais là j''avoue ne pas voir comment faire

    est ce quelqu'un a déjà fait cela en c# et comment ?

    merci de votre aide.

  2. #2
    Membre éprouvé Avatar de shaun_the_sheep
    Homme Profil pro
    Chef de projet NTIC
    Inscrit en
    Octobre 2004
    Messages
    1 619
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Chef de projet NTIC
    Secteur : Enseignement

    Informations forums :
    Inscription : Octobre 2004
    Messages : 1 619
    Points : 996
    Points
    996
    Par défaut
    j'ai trouvé une solution qui correspond à ma problématique, que je souhaite partager au cas ou quelqu'un cherche à faire de même

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
     
            /// <summary>
            /// Envoi un fichier de données à BlackBoard
            /// </summary>
            private void Push_BB_File(string studentFilePathForBB, string bb_URL, string bb_Login, string bb_Pwd)
            {
                byte[] fileStream = File.ReadAllBytes(studentFilePathForBB);
     
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
     
                WebRequest request = WebRequest.Create(bb_URL);
     
                request.ContentType = "text/plain";
                request.Method = "POST";
                request.Credentials = new NetworkCredential(bb_Login, bb_Pwd);
     
                // Get the request stream.
                Stream dataStream = request.GetRequestStream();
                // Write the data to the request stream.
                dataStream.Write(fileStream, 0, fileStream.Length);
                // Close the Stream object.
                dataStream.Close();
     
                // Get the response.
                WebResponse response = request.GetResponse();
     
                // Display the status.
                CurrentContext.Message.Display(((HttpWebResponse)response).StatusDescription);
                // Get the stream containing content returned by the server.
                dataStream = response.GetResponseStream();
                // Open the stream using a StreamReader for easy access.
                StreamReader reader = new StreamReader(dataStream);
                // Read the content.
                string responseFromServer = reader.ReadToEnd();
                // Display the content.
                CurrentContext.Message.Display(responseFromServer);
                // Clean up the streams.
                reader.Close();
     
     
            }

  3. #3
    Membre éprouvé Avatar de shaun_the_sheep
    Homme Profil pro
    Chef de projet NTIC
    Inscrit en
    Octobre 2004
    Messages
    1 619
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Chef de projet NTIC
    Secteur : Enseignement

    Informations forums :
    Inscription : Octobre 2004
    Messages : 1 619
    Points : 996
    Points
    996
    Par défaut
    j'ai grandement amélioré mon code pour traiter des fichiers volumineux

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
     
            /// <summary>
            /// Envoi un fichier de données à BlackBoard
            /// renvoi ID du log BB
            /// </summary>
            private string Push_BB_File(string studentFilePathForBB, string bb_URL, string bb_Login, string bb_Pwd)
            {   
                string dataSetUidLog = "";
                HttpWebRequest WRequest;
                HttpWebResponse WResponse;
     
                try
                {
                    //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
     
                    //preAuth the request
                    // You can add logic so that you only pre-authenticate the very first request.
                    // You should not have to pre-authenticate each request.
                    WRequest = (HttpWebRequest)HttpWebRequest.Create(bb_URL);
                    // Set the username and the password.
                    WRequest.Credentials = new NetworkCredential(bb_Login, bb_Pwd);
                    WRequest.PreAuthenticate = true;
                    WRequest.Method = "HEAD";
                    WRequest.Timeout = 10000;
                    WResponse = (HttpWebResponse)WRequest.GetResponse();
                    WResponse.Close();
     
                    // Make the real request
                    WRequest = (HttpWebRequest)WebRequest.Create(bb_URL);
                    WRequest.ContentType = "text/plain";
                    WRequest.Method = "POST";
                    WRequest.Credentials = new NetworkCredential(bb_Login, bb_Pwd);
                    WRequest.PreAuthenticate = true;
                    WRequest.Timeout = 10000;
                    WRequest.AllowWriteStreamBuffering = false;
     
                    FileStream ReadIn = new FileStream(studentFilePathForBB, FileMode.Open, FileAccess.Read);
                    ReadIn.Seek(0, SeekOrigin.Begin); // Move to the start of the file.
                    WRequest.ContentLength = ReadIn.Length; // Set the content length header to the size of the file.
                    Byte[] FileData = new Byte[ReadIn.Length]; // Read the file in 2 KB segments.
                    int DataRead = 0;
                    int bufferSize = 2048;
                    Stream tempStream = WRequest.GetRequestStream();
                    do
                    {
                        DataRead = ReadIn.Read(FileData, 0, bufferSize);
                        if (DataRead > 0) //we have data
                        {
                            tempStream.Write(FileData, 0, DataRead);
                            Array.Clear(FileData, 0, bufferSize); // Clear the array.
                        }
                    } while (DataRead > 0);
     
     
                    using (WResponse = WRequest.GetResponse() as HttpWebResponse)
                    {
                        CurrentContext.Message.Display("Content length is {0}", WResponse.ContentLength);
                        CurrentContext.Message.Display("Content type is {0}", WResponse.ContentType);
     
                        if (WResponse.StatusCode == HttpStatusCode.OK)
                        {
     
                            // Get the stream associated with the response.
                            Stream receiveStream = WResponse.GetResponseStream();
     
                            // Pipes the stream to a higher level stream reader with the required encoding format. 
                            StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
     
                            CurrentContext.Message.Display("Response stream received.");
                            string responseFromServer = readStream.ReadToEnd();
                            CurrentContext.Message.Display(responseFromServer);
                            dataSetUidLog = ExtactBB_DataSetUidLog(responseFromServer);
                            CurrentContext.Message.Display(dataSetUidLog);
     
                            WResponse.Close();
                            readStream.Close();
                        }
                    }
                }
                catch (WebException ex)
                {
                    using (var stream = ex.Response.GetResponseStream())
                    using (var reader = new StreamReader(stream))
                    {
                        CurrentContext.Message.Display(reader.ReadToEnd());
                    }
                }
                catch (Exception ex)
                {
                    // Something more serious happened
                    // like for example you don't have network access
                    // we cannot talk about a server exception here as
                    // the server probably was never reached
                }                        
     
                return dataSetUidLog;
            }

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. [phpMyAdmin] Comment envoyer des données sur ma bdd avec phpMyAdmin!
    Par webherbe dans le forum EDI, CMS, Outils, Scripts et API
    Réponses: 2
    Dernier message: 22/08/2011, 16h42
  2. [AC-2003] Comment envoyer des données access sur excel?
    Par maringot dans le forum VBA Access
    Réponses: 3
    Dernier message: 19/11/2009, 10h32
  3. Réponses: 5
    Dernier message: 09/10/2008, 20h14
  4. Réponses: 9
    Dernier message: 04/06/2008, 12h38
  5. Réponses: 16
    Dernier message: 21/03/2006, 00h21

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo