DotNet API Library to get access HostelsClub searchengine - asp.net

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();
}
}

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);
}

Send XML to a web service c#

How I can send XML to a web service from C#(.NET)?
Not using "add references"
And I want get response from the service
This code has no exceptions, but I think app can't autorize in web service
I do so
class Program
{
static void Main(string[] args)
{
string xml = "<message>"+
"<service id="+"single"+" source = "+"AlphaName"+"/>"+
"<to>number</to>"+
"<body content-type="+"text/plain"+">"+
"This is a sample message"+
"</body>"+
"</message>";
Program prog = new Program();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.life.com.ua/ip2sms/");
request.Credentials = new NetworkCredential("login", "password");
byte[] authBytes = Encoding.UTF8.GetBytes("login:password".ToCharArray());
request.Headers["Authorization"] = Convert.ToBase64String(authBytes);
prog.requests(xml);
}
}
XML request
String requests(string xml)
{
WebResponse result = null;
WebRequest req = null;
Stream newStream = null;
Stream ReceiveStream = null;
StreamReader sr = null;
string strOut = "";
try
{
req = WebRequest.Create("https://api.life.com.ua/ip2sms/");
req.Method = "POST";
req.Timeout = 120000;
//req.ContentType = "text/xml; charset = \"utf8\"";
req.ContentType = "application/x-www-form-urlencoded";
byte[] SomeBytes = null;
SomeBytes = UTF8Encoding.UTF8.GetBytes(xml);
req.ContentLength = SomeBytes.Length;
newStream = req.GetRequestStream();
newStream.Write(SomeBytes, 0, SomeBytes.Length);
newStream.Close();
// считываем результат работы
result = req.GetResponse();
ReceiveStream = result.GetResponseStream();
Encoding encode = Encoding.UTF8;
sr = new StreamReader(ReceiveStream, encode);
Char[] read = new Char[256];
int count = sr.Read(read, 0, 256);
while (count > 0)
{
String str = new String(read, 0, count);
strOut += str;
count = sr.Read(read, 0, 256);
}
}
catch (Exception ex)
{
}
return strOut;
}
but nothing happens.Thanks!

curl Request with 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);

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;
}

File Upload with HttpWebRequest doesn't post the file

Here is my code to post the file. I use asp fileupload control to get the file stream.
HttpWebRequest requestToSender = (HttpWebRequest)WebRequest.Create("http://localhost:2518/Web/CrossPage.aspx");
requestToSender.Method = "POST";
requestToSender.ContentType = "multipart/form-data";
requestToSender.KeepAlive = true;
requestToSender.Credentials = System.Net.CredentialCache.DefaultCredentials;
requestToSender.ContentLength = BtnUpload.PostedFile.ContentLength;
BinaryReader binaryReader = new BinaryReader(BtnUpload.PostedFile.InputStream);
byte[] binData = binaryReader.ReadBytes(BtnUpload.PostedFile.ContentLength);
Stream requestStream = requestToSender.GetRequestStream();
requestStream.Write(binData, 0, binData.Length);
requestStream.Close();
HttpWebResponse responseFromSender = (HttpWebResponse)requestToSender.GetResponse();
string fromSender = string.Empty;
using (StreamReader responseReader = new StreamReader(responseFromSender.GetResponseStream()))
{
fromSender = responseReader.ReadToEnd();
}
XMLString.Text = fromSender;
In the page load of CrossPage.aspx i have the following code
NameValueCollection postPageCollection = Request.Form;
foreach (string name in postPageCollection.AllKeys)
{
Response.Write(name + " " + postPageCollection[name]);
}
HttpFileCollection postCollection = Request.Files;
foreach (string name in postCollection.AllKeys)
{
HttpPostedFile aFile = postCollection[name];
aFile.SaveAs(Server.MapPath(".") + "/" + Path.GetFileName(aFile.FileName));
}
string strxml = "sample";
Response.Clear();
Response.Write(strxml);
I don't get the file in Request.Files. The byte array is created. What was wrong with my HttpWebRequest?
multipart/form-data doesn't consist of simply writing the file bytes to the request stream. You need to respect the RFC 1867. You may take a look at this post of how this could be done with multiple files.

Resources