简体   繁体   中英

JSON C# WebRequest returns error 400 bad request

Following code throws an error on request.GetResponse(). It returns an error 400 bad request. I tried different things but so far without any succes. Is there anything I can do to get more detail about the error 400?

string sURL = "https://testservice.mywebsite.be/games/1/players";
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sURL);
        request.Method = "POST";
        request.Accept = "application/json";
        request.ContentType = "application/json";

        String sTimestamp = DateTime.Now.ToUniversalTime().ToString("yyyyMMddHHmmss");
        string sHMACmessage = string.Format("verb={0}&timestamp={1}&url={2}&playernumber={3}", request.Method.ToString().ToUpperInvariant(), sTimestamp, sURL, sPlayerNumber);
        byte[] bHash = HashHMAC(StringEncode("myprivatekey"), StringEncode(sHMACmessage));
        string sHash = HashEncode(bHash);

        request.Headers.Add("Timestamp", sTimestamp);
        request.Headers.Add("PlayerNumber", sPlayerNumber);
        request.Headers.Add("Authentication", String.Concat("mypublickey", ":", sHash));

        using (var streamWriter = new StreamWriter(request.GetRequestStream()))
        {
            string json = "{\"playingYear\":\"2015\"}";
            streamWriter.Write(json);
        } 
        long length = 0;
        try
        {
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                length = response.ContentLength;
            }
        }
        catch (WebException ex)
        {
            throw;
        }

In the testservice, make sure you turn the following off to see a detailed error:

<?xml version="1.0"?>
<configuration>
<system.web>
    <customErrors mode="Off"/>
</system.web>
</configuration>

Also try using a tool like Fiddler to see if it works from there before trying with code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM