Execute curl request in 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 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

Related

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

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

How to create a request to a URL and write the response to the page

I believe I've done this before, but I can't seem to remember how:(
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("www.example.com");
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
How do I then write the response to the page?
Thanks a lot.
HttpWebRequest r = ( HttpWebRequest)WebRequest.Create("http://www.demo.com");
r.Method = "Get";
HttpWebResponse res = (HttpWebResponse)r.GetResponse();
Stream sr= res.GetResponseStream();
StreamReader sre = new StreamReader(sr);
string s= sre.ReadToEnd();
Response.Write(s);
The below example demonstrates how it can be done:
string myRequest = "abc=1&pqr=2&lmn=3";
string myResponse="";
string myUrl = "Where you want to post data";
System.IO.StreamWriter myWriter = null;// it will open a http connection with provided url
System.Net.HttpWebRequest objRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(myUrl);//send data using objxmlhttp object
objRequest.Method = "GET";
objRequest.ContentLength = TranRequest.Length;
objRequest.ContentType = "application/x-www-form-urlencoded";//to set content type
myWriter = new System.IO.StreamWriter(objRequest.GetRequestStream());
myWriter.Write(myRequest);//send data
myWriter.Close();//closed the myWriter object
System.Net.HttpWebResponse objResponse = (System.Net.HttpWebResponse)objRequest.GetResponse();//receive the responce from objxmlhttp object
using (System.IO.StreamReader sr = new System.IO.StreamReader(objResponse.GetResponseStream()))
{
myResponse= sr.ReadToEnd();
}
Then u can use the data in myResponse to display whatever is returned.
Hope this helps you...

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

How to dynamically invoke Web Services in .Net

I am writing a Web service client in C# which takes the URL of the web Service, and a web method name.
I want to check if thew Web method actually receives an int and returns a DataTable, and if this is true, it should call it and return the DataTable.
I have found a couple of posts where this is accomplished compiling dynamically the Proxy class.
But for my case this'd be too expensive, because the client is actually a WSS WebPart, and I don't want to do this every time the page is rendered; only when the properties are changed.
In the end of the day web service description is just an XML file. You can grab it by requesting service.asmx?WSDL:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:1753/Service1.asmx?WSDL");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string xml = reader.ReadToEnd();
Once you have service description you can parse it and check method signature. Then, you can invoke the method using HTTP POST:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:1753/Service1.asmx?HelloWorld");
request.Method = "POST";
request.ContentType = "application/soap+xml; charset=utf-8";
byte[] data = Encoding.UTF8.GetBytes(
#"<?xml version='1.0' encoding='utf-8'?>
<soap12:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap12='http://www.w3.org/2003/05/soap-envelope'>
<soap12:Body>
<HelloWorld xmlns='http://tempuri.org/' />
</soap12:Body>
</soap12:Envelope>");
request.ContentLength = data.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string xml = reader.ReadToEnd();
If the Web Service is always the same (i.e. the method is the same as well as what it returns) and uit's just the url that might change, then just add a web reference to the project with the webpart in it, the set the Url of the proxy like so:
using (var serviceProxy = new ServiceProxy())
{
serviceProxy.Url = somepropertysetbythewebpart;
// make call to method here
}
After a lot of resarching I found out how to do it. The code of the selected answer is almost there, but I had to add the SOAPAction in the header and also change the ContentType.
Here is the entire code:
var strRequest = #"<soap12:Envelope>
...
</soap12:Envelope>";
string webServiceUrl = "http://localhost:8080/AccontService.svc";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(webServiceUrl);
request.Method = "POST";
request.ContentType = "text/xml;charset=UTF-8";
request.Accept = "text/xml";
request.Headers.Add("SOAPAction", "http://tempuri.org/IAccountService/UpdateAccount");
byte[] data = Encoding.UTF8.GetBytes(strRequest);
request.ContentLength = data.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string responseXmlString = reader.ReadToEnd();
return new HttpResponseMessage()
{
Content = new StringContent(responseXmlString, Encoding.UTF8, "application/xml")
};

Resources