【问题标题】:Can not include request.ContentLength不能包含 request.ContentLength
【发布时间】:2017-05-05 18:14:14
【问题描述】:

我有一个我正在努力解决的附带问题,但决定在一个单独的问题中提出它,因为原始问题是冗长的,我认为这个问题的答案将解决 other question。 (一旦两个都解决了,我会更新另一个)

所以我正在 Visual Studio 2013 上执行 HttpWebRequest 并希望将 POST 添加到标题中。这工作正常,但最终服务器返回一个错误,说它不知道长度。所以从代码 sn-ps 我谷歌我应该能够只编码 request.ContentLength = byte1 其中 byte1 是头部参数的内容长度。但我的代码不会接受 .ContentLength 作为参数?为什么??

doco 说我可以,我包括使用 System.Net 和使用 System.Net.Http

那我做错了什么?

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.System;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Web;

 private async void VerifyUser()
         {
            loginParams = "username=" + logInUserIdString + "&password=" + logInPasswordString;
            string teamResponse = "https://mySite.com/teambeta/LoginApp?" + loginParams;
            Debug.WriteLine(teamResponse);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(teamResponse);


            request.Method = "POST";

           request.ContentType = "application/json;odata=verbose";



            System.Net.HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync();

            using (var sr = new StreamReader(response.GetResponseStream()))
            {
                logInString = sr.ReadToEnd();
            }

           Debug.WriteLine(logInString);
         }

注意:如果我不包含 request.Method = "POST" 它会没问题,但不会返回任何值。所以我也明白默认长度是-1,但我想将其更改为 loginParams 的长度。

帮助??

【问题讨论】:

    标签: c# visual-studio-2013 windows-8.1


    【解决方案1】:

    解决了!!!

    使用 Visual Studio 2013 执行 Http Web 请求和响应的正确过程是使用新的 HttpClient 类。我想它会是这样的,但就是找不到。

    因此,这里是执行 Http 请求的正确代码,例如登录或在我的情况下仅根据用户 ID 和密码验证用户是有效用户。

    private async void VerifyUser()
    {
            loginParams = "username=" + logInUserIdString + "&password=" + logInPasswordString;
            string teamResponse = "https:// mySite.com?" + loginParams;
            Debug.WriteLine(teamResponse);
    
            HttpClient client = new HttpClient();
    
            try
            {
                HttpResponseMessage response = await client.PostAsync(new Uri(teamResponse), null);
    
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
    
                Debug.WriteLine(responseBody);
            }
            catch (HttpRequestException e)
            {
                Debug.WriteLine("\nException Caught!");
                Debug.WriteLine("Message :{0} ", e.Message);
            }
    }
    

    非常感谢 Suvabrata 的帮助,因为您的 cmets 将我带向了这个解决方案的方向。

    【讨论】:

      【解决方案2】:

      如果您使用 Post 方法,它可能有请求流数据,但在您的情况下它通过 URL 发送,所以您的响应流是空的。

      request.ContentLength=0;
      

      会更好,但如果您在请求流中发送一些数据,那么只需将数据的字符长度设置为 ContentLength 即可。

      [更新]代码添加寻求帮助...

      using System;
      using System.Collections.Generic;
      using System.IO;
      using System.Linq;
      using System.Net;
      using System.Reflection;
      using System.Runtime.Serialization.Json;
      using System.ServiceModel;
      using System.Text;
      
      public interface ICommunication
              {
              string Communicate(string Uri,string Method, string Refrance, string ContentType, string Data);
              }
      
          public class JSONCommunication  :ICommunication
              {
              public JSONCommunication()
                  {
      
                  }
              #region ICommunication Members
              private CookieContainer Cookie = new CookieContainer();
              public string Communicate(string Uri, string Method, string Refrance, string ContentType, string Data)
                  {
                  HttpWebRequest web = (HttpWebRequest)WebRequest.Create(Uri);
                  web.Method = Method;
                  web.Referer = Refrance;
                  web.ContentLength = Data.Length;
                  web.CookieContainer = Cookie;
                  //web.KeepAlive = true;
                  web.ContentType = ContentType;
                  if (Data != string.Empty && Method.ToUpper()!="GET")
                      {
                      using (var Request = web.GetRequestStream())
                          {
                          Request.Write(
                              ASCIIEncoding.Default.GetBytes(Data), 
                              0,
                              (int) web.ContentLength);
                          }
      
                      }
                  web.AllowAutoRedirect = true;
                  var Response = web.GetResponse();
                  var ResquestStream = Response.GetResponseStream();
                  ICollection<byte> bt = new List<byte>();
                  while (true)
                      {
                      int i = ResquestStream.ReadByte();
                      if (i == -1)
                          break;
                      bt.Add((byte)i);
                      }
                  var output = ASCIIEncoding.Default.GetString(bt.ToArray());
                  return output;
                  }
      
              #endregion
              }
      

      【讨论】:

      • 这正是我想做的添加行:request.ContentLength = 0 或者它是什么但 .contentLength 似乎不是命名空间中的有效方法。这是我得到的错误: System.Net.HttpWebRequest 不包含 ContentLength 的定义,并且没有扩展方法 ContentLength 接受 System.Net.HttpWebRequest 类型的第一个参数(您是否缺少 using 指令或程序集引用? )
      • 我只用过:System.Net;
      • 只有 System.Net 没有区别
      猜你喜欢
      • 1970-01-01
      • 2020-11-09
      • 2020-04-06
      • 2011-08-24
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 2011-04-15
      • 2016-12-12
      相关资源
      最近更新 更多