繁体   English   中英

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

[英]Posting a json to a distant server(REST)

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

我首先创建url和request方法:

        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,这是客户端服务器上发生了超出您控制范围的错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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