How can I send a request contains Json and pdf file using httpWebRequest ?

Ghaida 0 Reputation points
2024-05-22T21:52:02.4066667+00:00

I have a service that I'm trying to consume on my code. The service in Postman is working fine, the request is Form-Data containing JSON and PDF file selected from the workspace, my issue here is how can I handle the request in my code, I had tried to use multiFormData and tried to write the contentType to form-data with the boundaries and disposition but unfortunately not have a clue what the right way to complete with since all of these is not working with me.

ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
314 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Lan Huang-MSFT 28,821 Reputation points Microsoft Vendor
    2024-05-23T07:16:13.8366667+00:00

    Hi @Ghaida,

    You didn't provide your code, so it's not quite clear where your problem is.

    You can refer to the code below.

    More information:Upload files with HTTPWebrequest (multipart/form-data)

    //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;
    }
    

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments