How to like a facebook post using PostID using C#? - c#

Hello friend I having problem to like a facebook post.
I am developing application in asp.net C#.
My code
public static string AppendQueryString(string key, string value)
{
return string.Format("{0}={1}&", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(value));
}
public string PostID { get; private set; }
var url = "https://graph.facebook.com/me/feed?access_token=" + <MY_AccessToken>;
var parameters = (AppendQueryString("privacy", "{\"value\": \"EVERYONE\"}"))+
AppendQueryString("message", "hi everybody this is test message");
var webRequest = WebRequest.Create(url);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(parameters);
webRequest.ContentLength = bytes.Length;
System.IO.Stream os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
os.Close();
var webResponse = webRequest.GetResponse();
StreamReader sr = null;
try
{
sr = new StreamReader(webResponse.GetResponseStream());
this.PostID = sr.ReadToEnd();
}
finally
{
if (sr != null) sr.Close();
}
How to like a post using PostID.?

Related

How to pass header and Body value using HttpWebRequest in C#?

Im trying to POST API credentials data to API through HttpWebRequest class in C#, like i have to pass "Content-Type:application/x-www-form-urlencoded" in Header, then have to pass "grant_type:client_credentials,client_id:ruban123,client_secret:123456" in Body to get response/token (as described in API reference).
Bellow i attached work which i did
public class DataModel
{
public string grant_type { get; set; }
public string client_id { get; set; }
public string client_secret { get; set; }
}
static void Main(string[] args)
{
try
{
DataModel dm = new DataModel();
dm.grant_type = "client_credentials";
dm.client_id = "ruban123";
dm.client_secret = "123456";
var credentials = dm.grant_type + dm.client_id + dm.client_secret;
#region Http Post
string messageUri = "https://sampleurl.apivision.com:8493/abc/oauth/token";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(messageUri);
request.Headers.Add("Authorization", "Basic " + credentials);
request.ContentType = "application/json";
request.Method = "POST";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string jsonModel = Newtonsoft.Json.JsonConvert.SerializeObject(dm);
streamWriter.Write(jsonModel);
streamWriter.Flush();
streamWriter.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
string jsonString = null;
using (StreamReader reader = new StreamReader(responseStream))
{
jsonString = reader.ReadToEnd();
Console.WriteLine();
reader.Close();
}
#endregion Http Post
}
catch (Exception ex)
{
}
}[API REFERENCE][1]
Here is correct HttpWebRequest using:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(pathapi);
request.Method = "POST";
string postData = "grant_type=client_credentials&client_id=ruban123&client_secret=123456";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] bytes = encoding.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = bytes.Length;
Stream newStream = request.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
HttpWebRequest approach is not relevant. Look at this question Setting Authorization Header of HttpClient
It looks like you missed setting of ContentLength property of HttpWebRequest. It should be equal number of bytes to send.
Se this link for more information:
https://learn.microsoft.com/en-us/dotnet/api/system.net.httpwebrequest.contentlength?view=netframework-4.8

I am trying to write a console app in c# that consume a web service running on tomcat, to perform a "PUT" method with an xml file

public static String TransferMessage(String uri, String resource,
String xml_data, Method httpmethod,
ReturnType returnType)
{
try
{
WebRequest request = WebRequest.Create(uri + resource);
request.Method = httpmethod.ToString();
request.ContentType = #"application/xml;";
//request.Headers.Add("Token", token);
request.Timeout = Convert.ToInt32((new TimeSpan(1, 0, 0)).TotalMilliseconds);
request.ContentLength = Encoding.UTF8.GetByteCount(xml_data);
if (httpmethod != Method.GET)
using (Stream stream = request.GetRequestStream())
{
stream.Write(Encoding.UTF8.GetBytes(xml_data), 0,
Encoding.UTF8.GetByteCount(xml_data));
stream.Flush();
stream.Close();
}
return getResponseContent(request.GetResponse());
}
catch(Exception e)
{
Console.WriteLine(e);
}
return null;
}
Main method:
var res_xml = MethodHelper.TransferMessage(endpoint, "/" + resource,xml,
MethodHelper.Method.PUT,
MethodHelper.ReturnType.XML);
I am getting this error
ERROR javax.xml.bind.UnmarshalException\n - with
linked exception:\n[org.xml.sax.SAXParseException; line Number: 1;
columnNumber: 1; Content is not allowed in prolog.]
try{
string contend = "";
using (var streamReader = new StreamReader(new FileInfo(#"C:\Users\absmbez\Desktop\temp\upload.xml").OpenRead()))
{
contend = streamReader.ReadToEnd();
}
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
webrequest.Method = "PUT";
webrequest.ContentType = "application/xml";
Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
byte[] requestData = enc.GetBytes(contend);
webrequest.ContentLength = requestData.Length;
using (var stream = webrequest.GetRequestStream())
{
stream.Write(requestData, 0, requestData.Length);
}
HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
StreamReader responseStream = new StreamReader(webresponse.GetResponseStream(), enc);
string result = string.Empty;
result = responseStream.ReadToEnd();
webresponse.Close();
return result;
}
catch (Exception e)
{
Console.WriteLine(e);
}

C# REST API Authenticate with Bearer Token

Trying to write a tool which downloads a .zip file from a server via REST API.
It works without any problems with SOAP-UI but my tool doesn't want to download any files.
Always getting this error:
Cannot send a content-body with this verb-type.
My POST-Requests work fine but GET-Requests make problems. I Think there is a problem with my Webrequest-Header.
The authentication has to look like this:
Bearer "Access Token"
Here is my code:
class RestProvider
{
protected string method;
protected string endpoint;
protected string resource;
protected string parameters;
public RestProvider(string method, string endpoint, string resource, string parameters)
{
this.method = method;
this.endpoint = endpoint;
this.resource = resource;
this.parameters = parameters;
}
public string GetResponse()
{
string resultString = string.Empty;
ASCIIEncoding enc = new ASCIIEncoding();
byte[] paramData = enc.GetBytes(parameters);
if (this.method == "post")
{
try
{
WebRequest request = WebRequest.Create(this.endpoint + this.resource);
request.Method = this.method;
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = paramData.Length;
Stream stream = request.GetRequestStream();
stream.Write(paramData, 0, paramData.Length);
stream.Close();
WebResponse response = request.GetResponse();
stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
resultString = sr.ReadToEnd();
sr.Close();
stream.Close();
}
catch(Exception ex)
{
resultString = "{\"errorMessages\":[\"" + ex.Message.ToString() + "\"],\"errors\":{}}";
}
}
else if(this.method == "get")
{
try
{
WebRequest request = WebRequest.Create(this.endpoint + this.resource);
request.Headers["Authorization"] = "Bearer " + Convert.ToBase64String(Encoding.Default.GetBytes(this.parameters));
request.Method = this.method;
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = paramData.Length;
Stream stream = request.GetRequestStream();
stream.Write(paramData, 0, paramData.Length);
stream.Close();
WebResponse response = request.GetResponse();
stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
resultString = sr.ReadToEnd();
sr.Close();
stream.Close();
}
catch (Exception ex)
{
resultString = "{\"errorMessages\":[\"" + ex.Message.ToString() + "\"],\"errors\":{}}";
}
}
return resultString;
}
}
Any ideas?

How to send a string to url in window phone?

I create a method in a class (not in phone app) :
public void testSend()
{
try
{
string url = "abc.com";
string str = "test";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
string Data = "data=" + str;
byte[] postBytes = Encoding.UTF8.GetBytes(Data);
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = postBytes.Length;
Stream requestStream = req.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
Stream resStream = response.GetResponseStream();
var sr = new StreamReader(response.GetResponseStream());
string responseText = sr.ReadToEnd();
}
catch (WebException)
{
}
but it get error like that :
'System.Net.HttpWebRequest' does not contain a definition for 'GetRequestStream' and no extension method 'GetRequestStream' accepting a first argument of type 'System.Net.HttpWebRequest' could be found (are you missing a using directive or an assembly reference?
I'm don't know how why?please help me
//Create web request for Post Method
public void testSend()
{
try
{
string url = "abc.com";
string str = "test";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.BeginGetRequestStream(SendRequest, req);
}
catch (WebException)
{
}
}
//Get Response and write body
private void SendRequest(IAsyncResult asyncResult)
{
string str = "test";
string Data = "data=" + str;
HttpWebRequest req= (HttpWebRequest)asyncResult.AsyncState;
byte[] postBytes = Encoding.UTF8.GetBytes(Data);
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = postBytes.Length;
Stream requestStream = req.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
request.BeginGetResponse(SendResponse, req);
}
//Get Response string
private void SendResponse(IAsyncResult asyncResult)
{
try
{
MemoryStream ms;
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
HttpWebResponse httpResponse = (HttpWebResponse)response;
string _responestring = string.Empty;
using (Stream data = response.GetResponseStream())
using (var reader = new StreamReader(data))
{
_responestring = reader.ReadToEnd();
}
}
catch (WebException)
{
}
}

How can i post a request with parameter from C#.net

I want to post a request on server using POST and webrequest?
I need to pass parameters as well while posting?
how can i pass the parameters while posting?
How can i do that???
Sample code...
string requestBody = string.Empty;
WebRequest request = WebRequest.Create("myursl");
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
//request.ContentLength = byte sXML.Length;
//System.IO.StreamWriter sw = new System.IO.StreamWriter(request.GetRequestStream());
//sw.Write(sXML);
//sw.Close();
HttpWebResponse res = (HttpWebResponse)request.GetResponse();
if (res != null)
{
using (StreamReader sr = new StreamReader(res.GetResponseStream(), true))
{
ReturnBody = sr.ReadToEnd();
StringBuilder s = new StringBuilder();
s.Append(ReturnBody);
sr.Close();
}
}
if (ReturnBody != null)
{
if (res.StatusCode == HttpStatusCode.OK)
{
//deserialize code for xml and get the output here
string s =ReturnBody;
}
}
NameValueCollection keyValues = new NameValueCollection();
keyValues["key1"] = "value1";
keyValues["key2"] = "value2";
using (var wc = new WebClient())
{
byte[] result = wc.UploadValues(url,keyValues);
}
you can try with this code
string parameters = "sample=<value>&other=<value>";
byte[] stream= Encoding.UTF8.GetBytes(parameters);
request.ContentLength = stream.Length;
Stream newStream=webRequest.GetRequestStream();
newStream.Write(stream,0,stream.Length);
newStream.Close();
WebResponse webResponse = request.GetResponse();

Categories

Resources