用Sharepoint Rest API创建列表项;结果是400错误的请求
问题描述:
我执行下面的代码:用Sharepoint Rest API创建列表项;结果是400错误的请求
using Microsoft.SharePoint.Client;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net;
using System.Security;
using System.Text;
namespace Sharepoint_sandbox {
class Program {
private static CookieContainer GetO365CookieContainer (SharePointOnlineCredentials credentials, string targetSiteUrl){
CookieContainer container = null;
Uri targetSite = new Uri (targetSiteUrl);
string cookieString = credentials.GetAuthenticationCookie (targetSite);
if (cookieString != null) {
string trimmedCookie = cookieString.TrimStart ("SPOIDCRL=".ToCharArray());
container = new CookieContainer();
container.Add (new Cookie ("SPOIDCRL", trimmedCookie, string.Empty, targetSite.Authority));
}
return container;
}
private static SharePointOnlineCredentials GetO365Credentials (string userName, string password) {
SecureString securePassword = new SecureString();
foreach (char c in password.ToCharArray())
securePassword.AppendChar (c);
return new SharePointOnlineCredentials (userName, securePassword);
}
private static string GetFormDigest (string siteUrl, ICredentials credentials, CookieContainer cc) {
string formDigest = null;
string resourceUrl = siteUrl + "/_api/contextinfo";
HttpWebRequest httpWebRequest = HttpWebRequest.Create (resourceUrl) as HttpWebRequest;
httpWebRequest.Credentials = credentials;
httpWebRequest.CookieContainer = cc;
httpWebRequest.Timeout = 10000;
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/json; odata=verbose";
httpWebRequest.Accept = "application/json;odata=verbose";
httpWebRequest.ContentLength = 0;
httpWebRequest.ContentType = "application/json";
string result;
using (WebResponse webResponse = httpWebRequest.GetResponse()) {
using (System.IO.StreamReader sr = new System.IO.StreamReader (webResponse.GetResponseStream())) {
result = sr.ReadToEnd();
}
}
var dObject = (JObject)JsonConvert.DeserializeObject (result);
foreach (var item in dObject["d"].Children()){
formDigest = item.First["FormDigestValue"].ToString();
}
return formDigest;
}
private static Tuple<string, List<string>> CreateListItem (string site, string userName, string password, string resourceUrl, string content) {
HttpWebRequest httpWebRequest = HttpWebRequest.Create (resourceUrl) as HttpWebRequest;
httpWebRequest.UseDefaultCredentials = false;
SharePointOnlineCredentials credentials = GetO365Credentials (userName, password);
httpWebRequest.Credentials = credentials;
httpWebRequest.CookieContainer = GetO365CookieContainer (credentials, site);
string formDigest = GetFormDigest (site, credentials, httpWebRequest.CookieContainer);
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add ("X-RequestDigest", formDigest);
httpWebRequest.Timeout = 10000;
httpWebRequest.ContentType = "application/json; odata=verbose";
httpWebRequest.Accept = "application/json; odata=verbose";
httpWebRequest.ContentLength = 0;
List<string> errorMessages = new List<string>();
string response = "";
try {
byte[] binary = Encoding.Unicode.GetBytes(content);
httpWebRequest.ContentLength = binary.Length;
using (System.IO.Stream requestStream = httpWebRequest.GetRequestStream()) {
requestStream.Write (binary, 0, binary.Length);
}
using (WebResponse webResponse = httpWebRequest.GetResponse()) {
using (System.IO.StreamReader sr = new System.IO.StreamReader (webResponse.GetResponseStream())) {
response = sr.ReadToEnd();
}
}
}
catch (WebException e) {
errorMessages.Add (e.Message);
if (e.Response != null && e.Response.GetResponseStream() != null) {
using (System.IO.StreamReader sr = new System.IO.StreamReader (e.Response.GetResponseStream())) {
errorMessages.Add (sr.ReadToEnd());
}
}
}
return new Tuple<string, List<string>> (response, errorMessages);
}
static void Main (string[] args) {
string site = "https://*******";
string user = "******";
string password = "******";
string resourceUrl = site + "/_api/Web/Lists(guid'0818cf14-4028-4c7d-adbc-489adb1c0cb4')/Items";
string content = "{ '__metadata': { 'type':'SP.Data.Test_x005f_1ListItem' }, 'Title': 'TestItem'}";
Tuple<string, List<string>> result = CreateListItem (site, user, password, resourceUrl, content);
Console.Write (result.Item1 + "\n" + string.Join ("\n", result.Item2));
Console.ReadKey();
}
}
}
结果是:
A távoli kiszolgáló a következő hibát küldte vissza: (400) Hibás kérelem.
{"error":{"code":"-1, Microsoft.SharePoint.Client.InvalidClientQueryException","message":{"lang":"hu-HU","value":"Invalid JSON. The property name '' is not valid. The name of a property cannot be empty."}}}
英语匈牙利文: 远程服务器返回错误:(400)错误的请求。
我不想忽略哪个属性是空的。如果第一个和最后一个字符的内容不是{和},那么错误是“无效的JSON。JSON内容中没有识别出令牌。” 如果内容为空{}或{},则误差同上(属性名称“”是无效的。......“)
你能帮我吗? 感谢
之间任何其他字符串
答
我宁愿利用StreamWriter class
而不是Encoding class
来避免任何编码问题。
在您的例子来设置请求主体更换:
byte[] binary = Encoding.Unicode.GetBytes(content);
httpWebRequest.ContentLength = binary.Length;
using (System.IO.Stream requestStream = httpWebRequest.GetRequestStream())
{
requestStream.Write(binary, 0, binary.Length);
}
与
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(content);
}
答
从Unicode改变编码UTF8解决问题:
来自:
byte[] binary = Encoding.Unicode.GetBytes(content);
到:
byte[] binary = Encoding.UTF8.GetBytes(content);
不幸的是,这是不行的,抛出一个延伸: 类型的未处理的异常“System.Net .ProtocolViolationException'发生在System.dll中 此异常是因为此代码未设置httpWebRequest.ContentLength属性。 –
它返回什么样的错误,它适用于我 –
@LászlóH。发生此错误的原因是,在删除行'httpWebRequest.ContentLength = 0;'后,请求体长显式设置为0,错误应该消失。 –