我尝试使用WebClient将数据发送到WebAPI。运行我的代码给出了标题中显示的例外。有人可以帮我吗?
在这里,我的代码的一部分带有标题定义
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", "f_k@1F7"));
wc.Credentials = wrCache;
byte[] htmlResult = wc.UploadData(URI, "POST", data);
您可以使用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;
}
设置内容长度属性和" contentlength"通过如下代码中将其添加到WebClient标题中。
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/json";
-
-
-
//wc.Headers[HttpRequestHeader.ContentLength] = contentLength;
wc.Headers.Add("Content-Length", 0); //if there is no request body to be sent
or
wc.Headers.Add("Content-Length", data.length.ToString());
-
-
-
-
byte[] htmlResult = wc.UploadData(URI, "POST", data);