Search code examples
c#restpdfposthttpwebrequest

How send a PDF by POST HttpWebRequest in C#


(i'm french, sorry for my english)
I don't find / understand how send a simple PDF file by post request at a webService (REST protocol).
I tried some examples but it's doesn't word. And when i use a , it's work, but i want do this in the code behind only !
My question is the title : How send this PDF file?
The url : https://test.website.fr/Website/api/transactions/" + sVal + "/contrat
PDF file : questions.pdf

Thanks. Iris Touchard


Solution

  • I found the solution :

    //Identificate separator
    string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
    //Encoding
    byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
    
    //Creation and specification of the request
    HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("https://test.website.fr/Website/api/transactions/" + sVal + "/contrat"); //sVal is id for the webService
    wr.ContentType = "multipart/form-data; boundary=" + boundary;
    wr.Method = "POST";
    wr.KeepAlive = true;
    wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
    
    string sAuthorization = "login:password";//AUTHENTIFICATION BEGIN
    byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(sAuthorization);
    string returnValue = System.Convert.ToBase64String(toEncodeAsBytes);
    wr.Headers.Add("Authorization: Basic " + returnValue); //AUTHENTIFICATION END
    Stream rs = wr.GetRequestStream();
    
    
    string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}"; //For the POST's format
    
    //Writting of the file
    rs.Write(boundarybytes, 0, boundarybytes.Length);
    byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(Server.MapPath("questions.pdf"));
    rs.Write(formitembytes, 0, formitembytes.Length);
    
    rs.Write(boundarybytes, 0, boundarybytes.Length);
    
    string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
    string header = string.Format(headerTemplate, "file", "questions.pdf", contentType);
    byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
    rs.Write(headerbytes, 0, headerbytes.Length);
    
    FileStream fileStream = new FileStream(Server.MapPath("questions.pdf"), FileMode.Open, FileAccess.Read);
    byte[] buffer = new byte[4096];
    int bytesRead = 0;
    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
    {
        rs.Write(buffer, 0, bytesRead);
    }
    fileStream.Close();
    
    byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
    rs.Write(trailer, 0, trailer.Length);
    rs.Close();
    rs = null;
    
    WebResponse wresp = null;
    try
    {
        //Get the response
        wresp = wr.GetResponse();
        Stream stream2 = wresp.GetResponseStream();
        StreamReader reader2 = new StreamReader(stream2);
        string responseData = reader2.ReadToEnd();
    }
    catch (Exception ex)
    {
        string s = ex.Message;
    }
    finally
    {
        if (wresp != null)
        {
            wresp.Close();
            wresp = null;
        }
        wr = null;
    }