一个连接多个请求休息服务

时间:2016-03-01 15:12:54

标签: c# web-services httpwebrequest connection-pooling

如何使用相同的服务发出多个请求?

我创建了一个静态httpWebRequest:

    private static HttpWebRequest request;
    //private static StreamReader streamReader;
    //private StreamWriter streamWriter;

    public CentralRestService2(LogFile log)
    {
        if (request == null)
        {
            request = (HttpWebRequest)WebRequest.Create("service address");
            request.Method = "POST";
            request.Accept = "*/*";
            request.ContentType = "application/json";
            request.Headers["Authorization"] = "username and password";
            request.KeepAlive = true;
         }

        using (var streamWriter = new StreamWriter(request.GetRequestStream()))
        {
            string body = new JavaScriptSerializer().Serialize(emailRequest);
            streamWriter.Write(body);

        }

        using (var streamReader = new StreamReader(response.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
        }
        response.Close();
     }

我收到错误消息,包括无法写入流。连接意外关闭。我似乎无法在任何地方找到答案!

1 个答案:

答案 0 :(得分:0)

不要创建静态HttpWebRequest 请求不代表连接,但它使用ServicePointManager为您管理底层TCP连接 每次需要发送请求时,只需创建HttpWebRequest的新实例。

更新:
如果您要为服务创建客户端,则应使用HttpClient代替:

// add reference to System.Net.Http and System.Net.Http.Formatting
using System.Net.Http;

// with a handler you can configure the client and its behavior
var handler = new HttpClientHandler();
var httpClient = new HttpClient(handler);
httpClient.BaseAddress = new Uri("service address");
httpClient.DefaultRequestHeaders.Add("Authorization", "username and password");
var response = await httpClient.PostAsJsonAsync(httpClient.BaseAddress, emailRequest);