将 json 发布到远程服务器 (REST)

Posting a json to a distant server(REST)

我想使用此代码将一些 json 数据发送到远程服务器(休息,在我的控制之外),按照我发送它的方式:

我首先创建 url 和请求方法:

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(gUrlDot);
        request.Method = "POST";
        Dictionary<String, String> lDictionary = new Dictionary<String, String>();
        System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
        Dot lDot= new Dot();
        serviceContext lserviceContext = new serviceContext();
        items litems = new items();
        lDot.rad = pClient;
        lDictionary.Add("companyId", "00230");
        lDictionary.Add("treatmentDate", lGlobals.FormatDateYYYYMMDD());
        lDictionary.Add("country", "FR");
        lDictionary.Add("language", "fr");
        lDictionary.Add("Id", "test");


        litems.contextItem = lDictionary;
        lDot.serviceContext = lserviceContext;
        lDot.serviceContext.items = litems;
        String Input=_Tools.JsonSerializer(lDot);
        log.Debug("Input Dot " + Input);

        Byte[] byteArray = encoding.GetBytes(Input);

        request.ContentLength = byteArray.Length;
        request.ContentType = @"application/json";

        using (Stream dataStream = request.GetRequestStream())
        {
            dataStream.Write(byteArray, 0, byteArray.Length);
        }

        long length = 0;

当我到达这里时,它因执行而崩溃:错误 500!

        try
        {
          using (var response = (HttpWebResponse)request.GetResponse())
            {
                length = response.ContentLength;
                string output = response.ToString();
                lTrace.AppendLine("-Flux Json recu => " + response.StatusCode + "  " + length);
                log.Debug("Output Dot " + output);

            }
           log.Info(LogsHelper.LogHeader("End processing Get list  ", pClient, Service.SrvGetList, "", lResponse.StatusCode, lResponse.StatusLabel, lResponse.ResponseObject, ref lTrace));

        }
        catch (Exception ex)
        {
            lResponse.StatusCode = StatusCodes.ERROR_COMMUNICATION;
            log.Error(LogsHelper.LogHeader("End processing Get list", pClient, Service.SrvGetList, "", lResponse.StatusCode, ex.Message, lResponse.ResponseObject, ref lTrace));
        }

        return lResponse;
    }

我在这里错过了什么?

500 错误表示您向其发出请求的服务器存在问题。您需要检查以确保两件事;

1) 确保您的请求格式正确,并且所请求的资源没有任何意外或无效值。

2) 您要与之交谈的服务器可以获取请求,并且它是最新的(如果您控制客户端)。

在任何一种情况下,出现 500 的最常见原因是客户端服务器出现了超出您控制范围的错误。