Search code examples
c#winformsput

Trying to upload with a PUT request


I am trying to change the price of an article using the websites API the documentation for it is at https://www.mkmapi.eu/ws/documentation/API_1.1:Stock

When run the class I get an error 417 Expectation Failed, which is described from the documentation as: Typically you get a 417 Expectation Failed HTTP status code, when your request has an XML body without the corresponding header and/or the body not sent as text, but its byte representation. Another possible reason for a 417 is, when you send body data with more than 1.024 bytes without adding the header Expect: to your request.

Any help would be appreciated. I should also say that the authentication is not the problem I can download my article prices.

public void UpdateMarketPrice(string MarketID, string NewPrice) 
{
    // https://www.mkmapi.eu/ws/documentation/API_1.1:Stock

    String finalResult;
    String method = "PUT";
    String url = "https://www.mkmapi.eu/ws/v1.1/stock";

    HttpWebRequest request = WebRequest.CreateHttp(url) as HttpWebRequest;
    OAuthHeader header = new OAuthHeader();
    request.Headers.Add(HttpRequestHeader.Authorization, header.getAuthorizationHeader(method, url));
    request.Method = method;
    request.ContentType = "text/xml; encoding='utf-8'";

    XElement xmlDoc = 
        new XElement("request",
            new XElement("article",
                new XElement("idArticle", MarketID),
                new XElement("idLanguage", 1),
                new XElement("comments", "Edited through the API"),
                new XElement("count", 7),
                new XElement("price", 11),
                new XElement("condition", "NM"),
                new XElement("isFoil", false),
                new XElement("isSigned", false),
                new XElement("isPlayset", false)
            )
        );

    String finalXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + xmlDoc.ToString();
    MessageBox.Show(finalXML);
    byte[] bytes = Encoding.ASCII.GetBytes(finalXML);
    request.ContentLength = bytes.Length;

    using (Stream putStream = request.GetRequestStream())
    {
        putStream.Write(bytes, 0, bytes.Length);
    }

    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
    {
        finalResult = reader.ReadToEnd();
    }

    MessageBox.Show(finalResult);
}

Solution

  • I have read that HttpWebRequest adds an "expect 100 continue" header to requests unless you turn it off. There are servers that possibly don't support this header. And will produce this 417 Expectation Failed message.

    You could try setting it to false:

    System.Net.ServicePointManager.Expect100Continue = false;
    

    So the header isn't sent.

    I've seen this suggested sollution to other similar questions also.