I am getting problems making a http POST. The API I am calling is asking for the content-length. But I am unsure how to do this.
Here is the code I have:
public static string publishClip(string instance_url, string sessionId, string clipId)
{
int trev = System.Text.ASCIIEncoding.Unicode.GetByteCount(instance_url + "/services/apexrest/DesktopClient/PublishClip/" + clipId);
WebRequest wrGETURL;
wrGETURL = WebRequest
.Create(instance_url
+ "/services/apexrest/DesktopClient/PublishClip/"
+ clipId);
wrGETURL.Method = "POST";
wrGETURL.ContentType = "application/json";
wrGETURL.ContentLength = trev;
wrGETURL.Headers.Add("Authorization", "Bearer " + sessionId);
Stream objStreamclipId = wrGETURL.GetResponse().GetResponseStream();
StreamReader objReader = new StreamReader(objStreamclipId);
return "trev";
}
Can anyone help me out please?
This is the error I am getting:
{"You must provide a request body if you set ContentLength>0 or SendChunked==true. Do this by calling [Begin]GetRequestStream before [Begin]GetResponse."}
var postData = ?;
byte[] bytes = encoding.GetBytes(postData);
wrGETURL.ContentLength = bytes.Length;
Is your postData Trev?
You will need to get the Bytes from your StreamReader objReader. To do so, see here: How to convert an Stream into a byte[] in C#? and count them.
Related
this my code for create session and upload file in onedrive
string url = "https://api.onedrive.com/v1.0/drive/root:/" + "Nopbackup" +":/" + "" + fileName +":/upload.createSession" + "";
var result = string.Empty;
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
//request.ContentType = "application/json";
request.ContentType = "contentType";
//request.ac = "application/json";
request.Headers.Add("Authorization", tokenType + " " + accessToken);
request.ContentLength = 0;
//byte[] requestData = Encoding.UTF8.GetBytes(url);
//using (Stream st = request.GetRequestStream())
// st.Write(requestData, 0, requestData.Length);
WebResponse response = request.GetResponse();
using (var streamReader = new StreamReader(response.GetResponseStream()))
result = streamReader.ReadToEnd();
its giving server bad request 400 error
I think the issue is the URL you're POSTing with. It looks like this:
string url = "https://api.onedrive.com/v1.0/drive/root:/" + "Nopbackup" +":/" + "" + fileName +":/upload.createSession" + "";
Which turns out to be
https://api.onedrive.com/v1.0/drive/root:/Nopbackup:/filename:/upload.createSession
You've got the colon syntax a little messed up, and the API doesn't know what to do with that (hence the bad request).
Try building the URL like this instead:
string url = "https://api.onedrive.com/v1.0/drive/root:/" + "Nopbackup" + "/" + fileName +":/upload.createSession";
And I think things will work better for you.
Wonder if someone could assist me please, what I'm trying to achieve is to send data from one site to another: So in my 'sending' site I have a page that that runs the following:
string message;
message = "DATA DATA DATA DATA!!!";
System.Net.WebRequest request = WebRequest.Create("http://clt-umbraco.test.clt.co.uk/storereceive/?data-response");
request.ContentType = "application/json";
request.Method = "POST";
request.Headers["X-Parse-Application-Id"] = "aaaaaaaaaaaaaaa";
request.Headers["X-Parse-REST-API-Key"] = "bbbbbbbbbbbbbbb";
byte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes("{\"channels\": [\"\"], \"data\": { \"alert\": \" " + message + "\" } }");
string result = System.Convert.ToBase64String(buffer);
Stream reqstr = request.GetRequestStream();
reqstr.Write(buffer, 0, buffer.Length);
reqstr.Close();
WebResponse response = request.GetResponse();
//jsonString.Text = response;
reqstr = response.GetResponseStream();
StreamReader reader = new StreamReader(reqstr);
jsonString.Text = reader.ReadToEnd();
And on my receiving site/page I have the following on page load:
string[] keys = Request.Form.AllKeys;
for (int i = 0; i < keys.Length; i++)
{
Response.Write(keys[i] + ": " + Request.Form[keys[i]] + "<br>");
}
I can see that this page load event is firing but the Request.Form.Allkeys object is empty where I would hope it would contain the data from the sending page. Obviously I'm going drastically wrong somewhere....could someone help please??
Thanks,
Craig
That is because You are not posting a form, you are uploading raw data.
Set
request.ContentType="application/x-www-form-urlencoded";
And populate your post data as such:
Key1=value1&key2=value2
You should also consider encoding the values with HttpServerUtility.UrlEncode
If you still wan't to send raw data though, then at the server end, you should read the incoming data like: (instead of Request.Form[])
byte[] requestRawData = Request.BinaryRead(Request.ContentLength);
response = requests.patch( "https://<manageraddress>/api/admin/configuration/v1/conference/1/", auth=('<user1>', '<password1>'), verify=False, data=json.dumps({'pin': '1234'}) https://tsmgr.tsecurevideo.com/api/admin/configuration/v1/conference/1/"
I have tried
HttpWebRequest httpWReq =(HttpWebRequest)WebRequest.Create(string.Format("https://tsmgr.tsecurevideo.com/api/admin/configuration/v1/conference/2/"));
Encoding encoding = new UTF8Encoding();
string postData = "{\"pin\":\"1234\"}";
byte[] data = encoding.GetBytes(postData);
httpWReq.ProtocolVersion = HttpVersion.Version11;
httpWReq.Method = "POST";
httpWReq.ContentType = "application/json";//charset=UTF-8";
string credentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes("admin" + ":" + "password"));
httpWReq.Headers.Add("Authorization", "Basic " + credentials);
httpWReq.ContentLength = data.Length;
Stream stream = httpWReq.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
string s = response.ToString();
StreamReader reader = new StreamReader(response.GetResponseStream());
I am getting the error
The remote server returned an error: (501) Not Implemented.
try to send credentials in this way
string auth = string.Format("{0}:{1}", "admin","password");
string data = Convert.ToBase64String(Encoding.ASCII.GetBytes(auth));
string credentials= string.Format("{0} {1}", "Basic", data );
httpWReq.Headers[HttpRequestHeader.Authorization] = credentials;
refer here for documentation in Encoding.ASCII
From the HTTP spec:
501 Not Implemented
The server does not support the functionality required to fulfill the request. This is the appropriate response when the server does not recognize the request method and is not capable of supporting it for any resource.
Sounds like the server doesn't support the PATCH method.
I'm working with Yandex Disk API (http://api.yandex.com/disk/doc/dg/reference/propfind_space-request.xml).
Having trouble with adding property in the request body (quota-available-bytes and quota-used-bytes)
public static string SpaceInfo(string path)
{
// Authorization.
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create("https://webdav.yandex.ru/");
webReq.Accept = "*/*";
webReq.Headers.Add("Depth: 0");
webReq.Headers.Add("Authorization: OAuth " + token);
webReq.Method = "PROPFIND";
// Adding data in body request.
string inputData = #"<D:propfind xmlns:D=""DAV:""><D:prop><quota-available-bytes/></D:prop></D:propfind>";
byte[] buffer = new ASCIIEncoding().GetBytes(inputData);
webReq.ContentType = "text/xml; encoding='utf-8";
webReq.ContentLength = buffer.Length;
try
{
HttpWebResponse resp = (HttpWebResponse)webReq.GetResponse();
StreamReader sr = new StreamReader(resp.GetResponseStream());
string dinfo = sr.ReadToEnd();
return dinfo;
}
}
I don't get any response, maybe i can use another method? What should i do?
Thanks!
quota-available-bytes should use same namespace "D"
I am attempting to do application oauth as outlined here: https://dev.twitter.com/docs/api/1.1/post/oauth2/token
but my attempts to do so result in 403(forbidden) The C# code I am attempting is:
String key = ConfigurationManager.AppSettings["TwitterConsumerKey"];
String secret = ConfigurationManager.AppSettings["TwitterConsumerSecret"];
String bearerCredentials = HttpUtility.UrlEncode(key) + ":" + HttpUtility.UrlEncode(secret);
bearerCredentials = Convert.ToBase64String(Encoding.UTF8.GetBytes(bearerCredentials));
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.twitter.com/oauth2/token");
request.Method = "POST";
request.Headers.Add("Authorization", "Basic " + bearerCredentials);
request.ContentType = "Content-Type: application/x-www-form-urlencoded;charset=UTF-8";
string postData = "grant_type=client_credentials";
byte[] data = System.Text.Encoding.UTF8.GetBytes(postData);
request.ContentLength = data.Length;
request.GetRequestStream().Write(data, 0, data.Length);
WebResponse response = request.GetResponse();
Any suggestions on what I am doing wrong here?
Leaving this question up in case someone else makes the same silly mistake I did, writing it up pointed out to me the answer this line
request.ContentType = "Content-Type: application/x-www-form-urlencoded;charset=UTF-8";
string postData = "grant_type=client_credentials";
had an unecessary Content-Type being set it should be
request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
string postData = "grant_type=client_credentials";