在JSon调用时请求超时错误

时间:2017-07-28 07:04:47

标签: c# asp.net json web-services rest

我用Newtonsoft创建了一个JSon对象。当我想将它传递给宁静的web服务并希望从它做出响应时,我得到“请求超时”错误,虽然我为请求设置了超时为-1或任何。问题出在哪里?

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://app.myservice.com/sendJSon");
    request.ContentType = "text/json";
    request.Method = "POST";
    request.Timeout = 200000;

    JObject asnInfo = CreateAsnInfo();

    JsonSerializer serializer = new JsonSerializer();
    using (var streamWriter = new StreamWriter(request.GetRequestStream()))
    {
        using (var writer = new JsonTextWriter(streamWriter))
        {
            serializer.Serialize(writer, asnInfo);
        }
    }
    var response = (HttpWebResponse)request.GetResponse();
    using (var streamReader = new StreamReader(response.GetResponseStream()))
    {
        var responseText = streamReader.ReadToEnd();
    }

1 个答案:

答案 0 :(得分:0)

你是代理人吗?该代码似乎与公共测试Web服务一起使用。

Link to .NET Fiddle working example

using System;
using System.IO;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public class Program
{
    public static void Main()
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://jsonplaceholder.typicode.com/posts");
        request.ContentType = "text/json";
        request.Method = "POST";
        request.Timeout = 200000;

        JObject asnInfo = JObject.Parse(@"{ title: 'foo', body: 'bar', userId: 1 }");

        JsonSerializer serializer = new JsonSerializer();

        using (var streamWriter = new StreamWriter(request.GetRequestStream()))
        {
            using (var writer = new JsonTextWriter(streamWriter))
            {
                serializer.Serialize(writer, asnInfo);
            }
        }

        var response = (HttpWebResponse)request.GetResponse();

        using (var streamReader = new StreamReader(response.GetResponseStream()))
        {
            var responseText = streamReader.ReadToEnd();

            Console.WriteLine(responseText);
        }
    }
}