0
votes

I would like to add an item to a list in sharepoint using below code:

protected string httpGetPost(string getPostMode, string url, string dataToPost = "")
{
    HttpWebRequest endpointRequest = (HttpWebRequest)WebRequest.Create(url);
    endpointRequest.Method = getPostMode;

    var credentialCache = new CredentialCache();
    credentialCache.Add(
      new Uri(endpointRequest.RequestUri.GetLeftPart(UriPartial.Authority)), // request url's host
      "Digest",  // authentication type 
      new NetworkCredential(userName, password) // credentials 
    );
    endpointRequest.Credentials = credentialCache;

    endpointRequest.Accept = "application/json;odata=verbose";
    endpointRequest.ContentType = "application/json;odata=verbose";

    if (!string.IsNullOrEmpty(dataToPost))
    {
        using (Stream dataStream = endpointRequest.GetRequestStream())
        {
            byte[] bs = Encoding.ASCII.GetBytes(dataToPost);
            dataStream.Write(bs, 0, bs.Length);
        }
    }
    using (var resp = endpointRequest.GetResponse())
    {
        var html = new StreamReader(resp.GetResponseStream()).ReadToEnd();
        return html;
    }
}

And call the above method using below code:

httpGetPost("POST", url, "{\"__metadata\": { \"type\": \"SP.Data.Test_x0020_ListListItem\" }, \"Title\": \"Test\", \"Column B\", \"BBB\"}");

Here's the data I'm posting:

{"__metadata": { "type": "SP.Data.Test_x0020_ListListItem" }, "Title": "Test", "Column B", "BBB"}

I've took a look at this website https://msdn.microsoft.com/en-us/library/office/dn292552.aspx, but the authorization is different, it's using an accesstoken, but here's the problem:

In this website: http://sharepoint.stackexchange.com/questions/69617/sharepoint-2013-oauth-url-to-get-token, it saids I can't get the accesstoken, so I used username and password to login the sharepoint, but here comes another problem:

A System.Net.WebException is thrown in var resp = endpointRequest.GetResponse(), the error is saying The remote server returned an error: (403) Forbidden.

The account is a domain admin as well as a sharepoint admin.

Why I'm still getting the 403 error?

For some reasons, I can only use the REST API to communicate with sharepoint.

1
Are you missing Domain name in network credential ....?vinayak hegde
@vinayakhegde I've checked the username and password, they're correct with the appropriate domain name, I've also tried logging in using that username and password in internet explorer and it works...User2012384
I can provide a REST example using the HttpClient to upload a file if you like. It's pretty easy to go this route. Is there some reason you don't want to use rest? It's similar to what you are doing and it works from anywhere, including store apps.Arcan.NET
@Arcan.NET OK, I'd love to take a look at your example, I can only use REST API since I have a request that the project itself don't want to use the sharepoint library.User2012384

1 Answers

1
votes

Here is a slightly different method to achieve your goals. Some of the objects are specific to Store Apps in this example, but they can all easily be replaced with other values in a standard app.

 public string digest()
 {
 String retVal = "";
 try
 {
 string url = "https://YourSite.com/";
 HttpClient client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
 client.BaseAddress = new System.Uri(url);
 string cmd = "_api/contextinfo";
 client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
 client.DefaultRequestHeaders.Add("ContentType", "application/json");
 client.DefaultRequestHeaders.Add("ContentLength", "0");
 StringContent httpContent = new StringContent("");
 var response = client.PostAsync(cmd, httpContent).Result;
 if (response.IsSuccessStatusCode)
 {
 string content = response.Content.ReadAsStringAsync().Result;
 JsonObject val = JsonValue.Parse(content).GetObject();
 JsonObject d = val.GetNamedObject("d");
 JsonObject wi = d.GetNamedObject("GetContextWebInformation");
 retVal = wi.GetNamedString("FormDigestValue");
 }
 }
 catch
 { }
 return retVal;
 }

 FileOpenPicker picker = new FileOpenPicker();
 picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
 picker.ViewMode = PickerViewMode.Thumbnail;
 // Filter to include a sample subset of file types.
 picker.FileTypeFilter.Clear();
 picker.FileTypeFilter.Add(".bmp");
 picker.FileTypeFilter.Add(".png");
 picker.FileTypeFilter.Add(".jpeg");
 picker.FileTypeFilter.Add(".jpg");
 // Open the file picker.
 StorageFile path = await picker.PickSingleFileAsync();
 if (path != null)
 {
 string url = "https://YourSite.com/Subsite/";
 HttpClient client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
 client.BaseAddress = new System.Uri(url);
 client.DefaultRequestHeaders.Clear();
 client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
 client.DefaultRequestHeaders.Add("X-RequestDigest", digest());
 client.DefaultRequestHeaders.Add("X-HTTP-Method", "POST");
 client.DefaultRequestHeaders.Add("binaryStringRequestBody", "true");
 IRandomAccessStream fileStream = await path.OpenAsync(FileAccessMode.Read);
 var reader = new DataReader(fileStream.GetInputStreamAt(0));
 await reader.LoadAsync((uint)fileStream.Size);
 Byte[] content = new byte[fileStream.Size];
 reader.ReadBytes(content);
 ByteArrayContent file = new ByteArrayContent(content);
 HttpResponseMessage response = await client.PostAsync("_api/web/lists/getByTitle(@TargetLibrary)/RootFolder/Files/add(url=@TargetFileName,overwrite='true')?@TargetLibrary='Project Photos'&@TargetFileName='TestUpload.jpg'", file);
 response.EnsureSuccessStatusCode();
 if (response.IsSuccessStatusCode)
 { }
 }