我用Newtonsoft创建了一个JSon对象。当我想将其传递给 restful 网络服务并想要从中响应时,我收到"请求超时"错误,尽管我将请求超时设置为 -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();
}
你在代理后面吗?该代码似乎适用于公共测试 Web 服务。
链接到 .NET 小提琴工作示例
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);
}
}
}