2017-02-28 447 views
1

我尝试使用WebClient将数据发送到webapi。运行我的代码会在标题中显示异常。 有人可以帮我吗?'Content-Length'标题必须使用适当的属性或方法进行修改。参数名称:名称

我用头定义

using (WebClient wc = new WebClient()) 
      { 
       wc.Headers[HttpRequestHeader.ContentType] = "application/json"; 
       wc.Headers[HttpRequestHeader.Authorization] = headerString; 

       data = Encoding.UTF8.GetBytes(jsonData); 
       string contentLength = data.Length.ToString(); 

       wc.Headers[HttpRequestHeader.ContentLength] = contentLength; 
       wc.Headers[HttpRequestHeader.Accept] = "application/json"; 

       wrCache = new CredentialCache(); 
       wrCache.Add(new Uri(URI), "Basic", new NetworkCredential("user1", "[email protected]")); 

       wc.Credentials = wrCache; 


       byte[] htmlResult = wc.UploadData(URI, "POST", data); 

回答

0

您可以使用HttpWebRequest代码下面的部分。例如:

private static HttpStatusCode UploadSharepointFile(string fileName) 
{ 
     // Read file from path 
     byte[] buffer = File.ReadAllBytes(fileName); 

     HttpWebRequest http = 
      WebRequest.CreateHttp($"https://google.com"); 

     http.Method = "POST"; 

     http.Credentials = (ICredentials) Program.cred; 

     http.Headers.Add("Accept", "application/json"); 
     http.ContentLength = buffer.Length; 
     http.GetRequestStream().Write(buffer, 0, buffer.Length); 

     HttpWebResponse response = (HttpWebResponse) http.GetResponse(); 
     return response.StatusCode; 
} 
相关问题