curl Request with ASP.NET - asp.net

I have read some other posts on Stack but I can't get this to work. It works fine on my when I run the curl command in git on my windows machine but when I convert it to asp.net it's not working:
private void BeeBoleRequest()
{
string url = "https://mycompany.beebole-apps.com/api";
WebRequest myReq = WebRequest.Create(url);
string username = "e26f3a722f46996d77dd78c5dbe82f15298a6385";
string password = "x";
string usernamePassword = username + ":" + password;
CredentialCache mycache = new CredentialCache();
mycache.Add(new Uri(url), "Basic", new NetworkCredential(username, password));
myReq.Credentials = mycache;
myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
WebResponse wr = myReq.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();
Response.Write(content);
}
This is the BeeBole API. Its pretty straight fwd. http://beebole.com/api but I am getting a following 500 error when I run the above:
The remote server returned an error: (500) Internal Server Error.

The default HTTP method for WebRequest is GET. Try setting it to POST, as that's what the API is expecting
myReq.Method = "POST";
I assume you are posting something. As a test, I'm going to post the same data from their curl example.
string url = "https://YOUR_COMPANY_HERE.beebole-apps.com/api";
string data = "{\"service\":\"absence.list\", \"company_id\":3}";
WebRequest myReq = WebRequest.Create(url);
myReq.Method = "POST";
myReq.ContentLength = data.Length;
myReq.ContentType = "application/json; charset=UTF-8";
string usernamePassword = "YOUR API TOKEN HERE" + ":" + "x";
UTF8Encoding enc = new UTF8Encoding();
myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(enc.GetBytes(usernamePassword)));
using (Stream ds = myReq.GetRequestStream())
{
ds.Write(enc.GetBytes(data), 0, data.Length);
}
WebResponse wr = myReq.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();
Response.Write(content);

Related

How to get the data from SAP to ASP.net using SAP GateWay Service

Please help how to get the data from SAP gate way services. SAP team given this url::-
http://Gateway_host:Gateway_port/sap/opu/odata/sap/ API SRV/ApplicationPendingListSet?$filter=UserID eq 'XXXXX' and user id & password. how to get this data in asp.net.
Please help.
string SAP_ODATA_URL = #"http://ApplicationURL";
string SAP_ODATA_QUERY = "MethodName?$filter=Parameter eq '" + extensionAttribute13 + "'";
string requestUrl = SAP_ODATA_URL + SAP_ODATA_QUERY;
WebRequest request = WebRequest.Create(requestUrl);
request.Method = WebRequestMethods.Http.Get;
request.ContentType = "application/json; charset=utf-8";
request.Credentials = new NetworkCredential("XXX", "XXX");
WebResponse response = request.GetResponse();
if (((HttpWebResponse)response).StatusCode == HttpStatusCode.OK)
{
Stream receiveStream = response.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream);
string responseFromServer = reader.ReadToEnd();
XmlTextReader xmlReader = new XmlTextReader(new StringReader(responseFromServer));
xmlReader.Read();
DataSet ds = new DataSet();
ds.ReadXml(xmlReader, XmlReadMode.Auto);
}

Execute curl request in ASP.net

I have read some other posts on Stack but I can't get this to work. It works fine on my when I run the curl in php code on my windows machine but when I convert it to asp.net it's not working
<%
Dim gv_rand_no, gv_ch, gv_email_id, gv__GET()
gv_rand_no = rand(0,99)
gv_ch = rand(0,99)
gv_email_id = gv__GET("email")
string url = "http://api.mycompany.com/post-api.php";
string data = "{\"id\":9970080, \"email\":\"gv_email_id\",\"method\":2,\"action_id\":110,\"random_number\":\"gv_rand_no\"}";
WebRequest myReq = WebRequest.Create(url);
myReq.Method = "POST";
myReq.ContentLength = data.Length;
myReq.ContentType = "application/json; charset=UTF-8";
using (Stream ds = myReq.GetRequestStream())
{
ds.Write(enc.GetBytes(data), 0, data.Length);
}
WebResponse wr = myReq.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();
Console.WriteLine(content);
Console.ReadLine();
%>
I am not familiar with ASP.net. i have converted code using of online code convertor
http://www.me-u.com/php-asp
please help me on this

download file from remote server asp.net

I am trying to download file from a file hosting server, using my username and password through my own website.
I already achieve the possibility to connect and download the file, with the code attached below.
my problem is this code doesn't support resume of download and my download manager isn't able to open more then one connection to the remote site ,so the speed is very low(the remote site Of course is supporting those features)
my main goal is to let me download this file with full speed and with the ability to resume the download in any Second.
this is the code
//the login method
ASCIIEncoding encoding = new ASCIIEncoding();
string url = "RemoteServerLoginPage/loginPage";
string postVariables = "id=myIdToTheServer";
postVariables += "&password=MyPasswordToTheServer";
// create the POST request
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
CookieContainer cookies = new CookieContainer();
webRequest.CookieContainer = cookies;
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = postVariables.Length;
byte[] data = encoding.GetBytes(postVariables);
Stream newStream = webRequest.GetRequestStream();
// Send the request
newStream.Write(data, 0, data.Length);
HttpWebResponse resp = (HttpWebResponse)webRequest.GetResponse();
using (Stream stream = resp.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
String responseString = reader.ReadToEnd();
}
//after login get the file with thr right cookies
string url2 = "UrlOfRemoteServerFileAdress/filename.rar";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url2);
req.CookieContainer = cookies;
HttpWebResponse resp2 = (HttpWebResponse)req.GetResponse();
////Initialize the output stream
Response.Clear();
Response.AppendHeader("Content-Disposition:", "attachment; filename=myfile.rar");
Response.AppendHeader("Content-Length:", "bytes");
Response.AppendHeader("Connection:", "Keep-Alive");
Response.ContentType = "application/octet-stream";
Response.AppendHeader("AcceptRanges", resp2.ContentLength.ToString());
const int BufferLength = 4 * 1024 * 1024;
byte[] byteBuffer = new byte[BufferLength];
Stream rs = req.GetResponse().GetResponseStream();
int len = 0;
while ((len = rs.Read(byteBuffer, 0, byteBuffer.Length)) > 0)
{
if (len < BufferLength)
{
Response.BinaryWrite(byteBuffer.Take(len).ToArray());
}
else
{
Response.BinaryWrite(byteBuffer);
}
Response.Flush();
}

Using Bit.ly API in ASP.NET 2.0

Hey I was wondering if anyone can point me to some example on how to use Bit.ly API in ASP.NET 2.0
I've done a really quick convert from an answer I found in VB.
I haven't tested this (sorry) but it may be of some help in the meantime, and I will sort it out to be a bit more C# style friendly.
public static string BitlyIt(string user, string apiKey, string strLongUrl)
{
StringBuilder uri = new StringBuilder("http://api.bit.ly/shorten?");
uri.Append("version=2.0.1");
uri.Append("&format=xml");
uri.Append("&longUrl=");
uri.Append(HttpUtility.UrlEncode(strLongUrl));
uri.Append("&login=");
uri.Append(HttpUtility.UrlEncode(user));
uri.Append("&apiKey=");
uri.Append(HttpUtility.UrlEncode(apiKey));
HttpWebRequest request = WebRequest.Create(uri.ToString()) as HttpWebRequest;
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
request.ServicePoint.Expect100Continue = false;
request.ContentLength = 0;
WebResponse objResponse = request.GetResponse();
XmlDocument objXML = new XmlDocument();
objXML.Load(objResponse.GetResponseStream());
XmlNode nShortUrl = objXML.SelectSingleNode("//shortUrl");
return nShortUrl.InnerText;
}
Original code taken from here -
http://www.dougv.com/blog/2009/07/02/shortening-urls-with-the-bit-ly-api-via-asp-net/
I found the answer from tim and it's pretty solid. I needed a vb.net version so converted it back from C# - I figured this may help someone. It appears the the bit.ly link has changed; not sure if the version is necessary anymore; added a little error handling in case you pass in a bad url.
Public Shared Function BitlyIt(ByVal strLongUrl As String) As String
Dim uri As New StringBuilder("http://api.bitly.com/v3/shorten?")
'uri.Append("version=2.0.1") 'doesnt appear to be required
uri.Append("&format=xml")
uri.Append("&longUrl=")
uri.Append(HttpUtility.UrlEncode(strLongUrl))
uri.Append("&login=")
uri.Append(HttpUtility.UrlEncode(user))
uri.Append("&apiKey=")
uri.Append(HttpUtility.UrlEncode(apiKey))
Dim request As HttpWebRequest = TryCast(WebRequest.Create(uri.ToString()), HttpWebRequest)
request.Method = "GET"
request.ContentType = "application/x-www-form-urlencoded"
request.ServicePoint.Expect100Continue = False
request.ContentLength = 0
Dim objResponse As WebResponse = request.GetResponse()
Dim myXML As New StreamReader(objResponse.GetResponseStream())
Dim xr = XmlReader.Create(myXML)
Dim xdoc = XDocument.Load(xr)
If xdoc.Descendants("status_txt").Value = "OK" Then
Return xdoc.Descendants("url").Value
Else
Return "Error " & "ReturnValue: " & xdoc.Descendants("status_txt").Value
End If
End Function
there is a bit shorter version of BitlyIn
public static string BitlyEncrypt2(string user, string apiKey, string pUrl)
{
string uri = "http://api.bit.ly/shorten?version=2.0.1&format=txt" +
"&longUrl=" + HttpUtility.UrlEncode(pUrl) +
"&login=" + HttpUtility.UrlEncode(user) +
"&apiKey=" + HttpUtility.UrlEncode(apiKey);
HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
request.ServicePoint.Expect100Continue = false;
request.ContentLength = 0;
return (new StreamReader(request.GetResponse().GetResponseStream()).ReadToEnd());
}
Migrating from v3 to v4 of the Bitly API - Bitly V4 code for ASP.NET Applications
public string Shorten(string groupId, string token, string longUrl)
{
//string post = "{\"group_guid\": \"" + groupId + "\", \"long_url\": \"" + longUrl + "\"}";
string post = "{ \"long_url\": \"" + longUrl + "\"}";// If you've a free account.
string shortUrl = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api-ssl.bitly.com/v4/shorten");
try
{
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
request.ServicePoint.Expect100Continue = false;
request.Method = "POST";
request.ContentLength = post.Length;
request.ContentType = "application/json";
request.Headers.Add("Cache-Control", "no-cache");
request.Host = "api-ssl.bitly.com";
request.Headers.Add("Authorization", "Bearer " + token);
using (Stream requestStream = request.GetRequestStream())
{
byte[] postBuffer = Encoding.ASCII.GetBytes(post);
requestStream.Write(postBuffer, 0, postBuffer.Length);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader responseReader = new StreamReader(responseStream))
{
string json = responseReader.ReadToEnd();
shortUrl = Regex.Match(json, #"""link"": ?""(?[^,;]+)""").Groups["link"].Value;
//return Regex.Match(json, #"{""short_url"":""([^""]*)""[,}]").Groups[1].Value;
}
}
}
}
catch (Exception ex)
{
LogManager.WriteLog(ex.Message);
}
if (shortUrl.Length > 0) // this check is if your bit.ly rate exceeded
return shortUrl;
else
return longUrl;
}

DotNet API Library to get access HostelsClub searchengine

i am developing a application to make reservation and searching on www.hostelclub.com from my website. for that i have got a library and API Document. but both are in php. please give me a download link from where i can download it API library and docuemnt.
from code below we can ping HostelsClub in asp.net:
string targetUri = "http://www.hostelspoint.com/xml/xml.php";
System.Xml.XmlDocument reqDoc = new System.Xml.XmlDocument();
reqDoc.Load(Server.MapPath("~\\ping.xml"));
string formParameterName = "OTA_request";
string xmlData = reqDoc.InnerXml;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUri);
string sendString = formParameterName + "=" + HttpUtility.UrlEncode(xmlData);
//string sendString = HttpUtility.UrlEncode(xmlData);
byte[] byteStream;
byteStream = System.Text.Encoding.UTF8.GetBytes(sendString);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteStream.LongLength;
using (Stream writer = request.GetRequestStream())
{
writer.Write(byteStream, 0, (int)request.ContentLength);
writer.Flush();
}
HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
string respStr = "";
if (request.HaveResponse)
{
if (resp.StatusCode == HttpStatusCode.OK || resp.StatusCode == HttpStatusCode.Accepted)
{
StreamReader respReader = new StreamReader(resp.GetResponseStream());
respStr = respReader.ReadToEnd(); // get the xml result in the string object
XmlDocument doc = new XmlDocument();
doc.LoadXml(respStr);
Label1.Text = doc.InnerXml.ToString();
}
}

Resources