不能包含request.ContentLength

时间:2014-03-03 04:17:25

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

我有一个方面的问题,我正在努力,但决定在一个单独的问题中提出它,因为原来的问题很长,我认为这个问题的答案将解决other question。 (一旦解决了,我会更新另一个)

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

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);
         }

注意:如果我不包含请求.Method =" POST"它会好的,但没有任何价值。所以我也理解默认长度为-1但我想将其更改为loginParams的长度。

HELP ??

2 个答案:

答案 0 :(得分: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的帮助,因为你的评论让我朝着这个解决方案的方向前进。

答案 1 :(得分:0)

如果你使用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
        }