Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
My code is perfect (AFAIK), but it's not passing along the body data in the HttpWebRequest:

C#
string uri = string.Format("http://192.168.125.50:28642/api/DeliveryItems/PostArgsAndXMLFileAsStr?serialNum={0}&siteNum={1}", serNum, siteNum);
SendXMLFile(fullXMLFilePath, uri);

public static string SendXMLFile(string xmlFilepath, string uri)
{
    StringBuilder sb = new StringBuilder();
    using (StreamReader sr = new StreamReader(xmlFilepath))
    {
        String line;
        while ((line = sr.ReadLine()) != null)
        {
            sb.AppendLine(line);
        }
    }

    string strData = sb.ToString();
    HttpWebRequest request = CreateRequest(uri, HttpMethods.POST, strData, "application/xml");

    request.KeepAlive = false;
    request.ProtocolVersion = HttpVersion.Version10;

    try
    {
        using (var response = (HttpWebResponse)request.GetResponse())
        {
            return response.GetResponseStream().ToString();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("SendXMLFile exception " + ex.Message);
        request.Abort();
        return string.Empty;
    }
}

public static HttpWebRequest CreateRequest(string uri, HttpMethods method, string data, string contentType)
{
    WebRequest request = HttpWebRequest.Create(uri);
    request.Method = Enum.ToObject(typeof(HttpMethods), method).ToString();
    request.ContentType = contentType;
    ((HttpWebRequest)request).Accept = contentType;
    if (method != HttpMethods.GET && method != HttpMethods.DELETE)
    {
        Encoding encoding = Encoding.UTF8;
        request.ContentLength = encoding.GetByteCount(data);
        request.ContentType = contentType;
        request.GetRequestStream().Write(
          encoding.GetBytes(data), 0, (int)request.ContentLength);
        request.GetRequestStream().Close();
    }
    else
    {
        // If we're doing a GET or DELETE don't bother with this
        request.ContentLength = 0;
    }
    // Finally, return the newly created request to the caller.
    return request as HttpWebRequest;
}


What in the above is lacking to send the contents of the file at xmlFilepath along with the HttpWebRequest?
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900