【问题标题】:Posting a json to a distant server(REST)将 json 发布到远程服务器(REST)
【发布时间】:2016-10-26 18:30:16
【问题描述】:

我想按照我发送的方式使用此代码将一些 json 数据发送到远程服务器(Rest,不受我控制):

我先创建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;
    }

我在这里错过了什么?

【问题讨论】:

  • 您是否从服务器收到任何消息错误(例如使用 fiddler 进行调试)? Http状态码“500”表示服务器内部错误,如果你的请求有效,错误可能来自远程服务器。

标签: c# json web-services rest internal-server-error


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-04
    • 2014-08-31
    • 1970-01-01
    • 2018-12-12
    • 2013-07-16
    相关资源
    最近更新 更多