I want to display image recieved from webresponse to browser directly without saving to a file.i have used below code to save the image to file but i want to display in browser directly.the website provides the captcha image in webresponse which i want to display.please help me.
public void captcha(string id, string pass)
{
HttpWebRequest req;
HttpWebResponse response;
string strNewValue,ckuser,ckpass;
System.Drawing.Image returnval;
ckuser = id;
ckpass = pass;
this.req = (HttpWebRequest)WebRequest.Create("http://site2sms.com/security/captcha.asp");
ServicePointManager.Expect100Continue = false;
this.req.CookieContainer = new CookieContainer();
this.req.AllowAutoRedirect = false;
this.req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/8.0";
this.req.Accept = "*/*";
this.req.Method = "POST";
this.req.CookieContainer = cookieCntr;
this.req.ContentType = "application/x-www-form-urlencoded";
this.req.Referer = "http://site2sms.com/verification.asp?source=login";
this.strNewValue = "user=" + ckuser + "&password=" + ckpass + "&Submit=Sign+in";
this.req.ContentLength = this.strNewValue.Length;
StreamWriter writer = new StreamWriter(this.req.GetRequestStream(), Encoding.ASCII);
writer.Write(this.strNewValue);
writer.Close();
this.response = (HttpWebResponse)this.req.GetResponse();
returnval = Image.FromStream(response.GetResponseStream());
// returnval.Save( Server.MapPath("captcha.bmp"));
Response.AppendHeader("Content-Disposition:", "inline;filename=captcha.bmp");
Response.ContentType = "image/bmp";
Response.Write(returnval);
Response.End();
this.response.Close();
}
You can use HttpResponse.WriteFile method to send the stream to client directly.
Writes the specified file directly to an HTTP response output stream.
You can create the IHttpHandler to send the stream, thus avoid some page life circle, increase the performance. Here is the link
Related
I have a WCF service that is consuming a website. Before anyone points out the obvious flaw and inherent instability in this approach, please forgive me, i have been forced to work on this.
The flow of the transaction is as follows :
Channel -> WCF Service ->(HTTP POST/GET) -> Website
Steps :
PostStrOnUrlRandom is called in a loop, passing it the string to be posted(strPost), the url(url) and CookieJar(CookieJarR) containig cookies from previous post.
HTTP GET on the url(not in below code)
I get the HTML page in response, parse it using XPATH, confirm it is correct page and save Cookies
POST strPost passed on this method on the url.
Get response HTML page, parse it using XPATH
Fetch next url and strPost from DB
Post the next strPost on the next url
I have to do this for 5 urls. Then i have to send response back to the Channel. The Channel then sends me another request, and i have to do another POST. I do this by using the same cookies I used for previous requests.
This is where the problem arises, I get back an Internal Server Error 500. If i do retires on this POST, using the same strPost, url and Cookies it works after 3-4 retires. I cannot understand why this is.
Code is as follows :
public HttpWebPostResponse PostStrOnUrlRandom(string url, string strPost, string Refer, CookieCollection cookieJarR)
{
log.Debug("Method Entery [PostStrOnUrl]");
StreamWriter myWriter = null;
string resultHtml = null;
HttpWebResponse objResponse = null;
HttpWebPostResponse hpr = null;
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.ProtocolVersion = HttpVersion.Version10;
objRequest.Timeout = 90000;
objRequest.CookieContainer = cookieJar;
objRequest.Method = "POST";
objRequest.ContentType = "application/x-www-form-urlencoded";
objRequest.AllowAutoRedirect = true;
objRequest.MaximumAutomaticRedirections = 100;
objRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0";
objRequest.Referer = Refer;
objRequest.Host = ConfigurationManager.AppSettings["Host"];
objRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
objRequest.Headers.Add("Origin", ConfigurationManager.AppSettings["Origin"]);
objRequest.Headers.Add("Cache-Control", "max-age=0");
objRequest.Headers.Add("Accept-Encoding", "gzip, deflate, br");
objRequest.Headers.Add("Accept-Language", "en-US,en;q=0.8");
objRequest.KeepAlive = true;
log.Debug("Making HttpWebRequest to" + url);
Uri target = new Uri(url);
log.Debug("Target Url : " + url.ToString());
foreach (Cookie cookie in cookieJarR)
{
objRequest.CookieContainer.Add(cookie);
cookieJar.Add(cookie);
log.Debug(cookie.Name + "" + cookie.Value + "" + "" + cookie.Domain);
}
try
{
myWriter = new StreamWriter(objRequest.GetRequestStream());
myWriter.Write(strPost);
log.Debug("Posting on Url StrPost =" + strPost);
}
catch (Exception e)
{
log.Debug(e.Message);
}
finally
{
myWriter.Close();
}
log.Debug("Making Request.");
try
{
objResponse = (HttpWebResponse)objRequest.GetResponse();
using (StreamReader sr =
new StreamReader(objResponse.GetResponseStream()))
{
resultHtml = sr.ReadToEnd();
sr.Close();
}
hpr = new HttpWebPostResponse(objResponse.ResponseUri.ToString(), resultHtml, objResponse.StatusCode.ToString());
return hpr;
}
catch (Exception e)
{
log.Error(e.Message);
log.Error("Exception", e.InnerException);
return null;
}
}
i am integrating rightmove real time data feed (rtdf) in my property site for listing my properties on rightmove website. i am using asp.net web api to post data on rightmove listing.
they have provide me with these SSL Files [.p12,.pem,.jks]. i have imported .p12 certificate in my local machine personal store and sending it in my http request
to rightmove test api link provide by rightmove.
i am getting the following error from server.
The remote server returned an error: 403 forbidden.
i checked my certificate loaded successfully in the request, below is my code
public static string PostData(string data, string url)
{
String result = "";
try
{
byte[] bytebuffer = Encoding.UTF8.GetBytes(data);
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Method = "POST";
objRequest.ContentLength = bytebuffer.Length;
objRequest.ContentType = "application/json";
objRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0";
objRequest.PreAuthenticate = true;
objRequest.Accept = "application/json";
objRequest.ClientCertificates.Add(CertificateHelper.GetRightmoveApiX509Certificate());
using (Stream stream = objRequest.GetRequestStream())
{
stream.Write(bytebuffer, 0, bytebuffer.Length);
stream.Close();
}
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
using (StreamReader streamReader = new StreamReader(objResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
// Close and clean up the StreamReader
streamReader.Close();
}
}
catch (Exception e)
{
result = "Exception: " + e.Message;
}
return result;
}
help me to get rid from 403 forbidden error.
Use the following.
I have tested it and it's working fine in my case.
// Grab Certificate
X509Certificate2 cert2 = new X509Certificate2(
AppDomain.CurrentDomain.BaseDirectory + "CertificateName.p12",
CertificatePasswordHere,
X509KeyStorageFlags.MachineKeySet);
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://adfapi.adftest.rightmove.com/v1/property/sendpropertydetails");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.ClientCertificates.Clear();
httpWebRequest.ClientCertificates.Add(cert2);
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(data);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
I created an windows form application that goes to a website and does a HTTPwebrequest POST and then displays the result in a webbrowser. I tested it on the computer that I wrote the program on and it works exactly like it should. However when I get the .exe file from the bin folder along with htmlagilitypack.dll and run a test on another computer, it does the POST data but web page that shows up in broswer is just the default login page. I have looked at it on fiddler and it seems like the cookies aren't getting set to the webbrowser. How can I fix this? I have also compiled the program in release mode and transferred the files in the release folder and its the same result.
On the program I used this to set the cookie for the browser.
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool InternetSetCookie(string lpszUrlName, string lpszCookieName, string lpszCookieData);
Does it have to do something with that dll file?
Edit: I have made sure both computer has 4.5 NET installed.
//get the cookie first
CookieCollection cookies = new CookieCollection();
CookieContainer cookiecontainer = new CookieContainer();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.supremenewyork.com" + url);
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
//get the auth token
using (StreamReader authreader = new StreamReader(request.GetResponse().GetResponseStream()))
{
source = authreader.ReadToEnd();
}
//need the auth token
string token = Regex.Match(source, "authenticity_token.+?value=\"(.+?)\"").Groups[1].Value;
//need the POST url
string action = Regex.Match(source, "UTF-8.+?action=\"(.+?)\"").Groups[1].Value;
//get the reponse from the server and save the cookies from the first request
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
cookies = response.Cookies;
response.Close();
string formparam = string.Format("utf8=%E2%9C%93&authenticity_token={0}&size={1}&commit=add to cart", token, sizechart[0]);
HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create("http://www.supremenewyork.com"+ action);
webreq.CookieContainer = new CookieContainer();
webreq.CookieContainer = request.CookieContainer;
//webreq.CookieContainer.Add(cookies); //recover the cookie first request
webreq.Method = "POST"; //set a POST method
webreq.Referer = "http://www.supremenewyork.com" + url;
webreq.ContentType = "application/x-www-form-urlencoded";
webreq.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36";
webreq.KeepAlive = true;
webreq.AllowAutoRedirect = true;
byte[] bytes = Encoding.UTF8.GetBytes(formparam);
webreq.ContentLength = bytes.Length;
//write
Stream postdata = webreq.GetRequestStream(); //open connection
postdata.Write(bytes, 0, bytes.Length); //send the data
postdata.Close();
//get the final response from the server
HttpWebResponse resp = (HttpWebResponse)webreq.GetResponse();
cookies = resp.Cookies;
response.Close();
//Stream answer = resp.GetResponseStream();
//StreamReader _answer = new StreamReader(webreq.GetResponse().GetResponseStream());
//string reply = _answer.ReadToEnd();
//need to check if item has been added to cart
//richTextBox1.Text = reply;
//check if item has been added to cart
HttpWebRequest webreq2 = (HttpWebRequest)WebRequest.Create("http://www.supremenewyork.com/shop/cart");
//webreq2.CookieContainer = new CookieContainer();
webreq2.CookieContainer = webreq.CookieContainer;
HttpWebResponse resp2 = (HttpWebResponse)webreq2.GetResponse();
Stream answer2 = resp2.GetResponseStream();
StreamReader _answer2 = new StreamReader(webreq2.GetResponse().GetResponseStream());
string reply2 = _answer2.ReadToEnd();
string item = textBoxkeyword.Text;
string color = textBoxcolor.Text.ToLower();
if(reply2.Contains(color))
{
//proceed to check out
//update user
appendtext(nDateTime + item + " " + color + " added to cart" );
appendtext(nDateTime + "Please check out the item");
HttpWebRequest webreq3 = (HttpWebRequest)WebRequest.Create("http://www.supremenewyork.com/checkout");
//webreq3.CookieContainer = new CookieContainer();
webreq3.CookieContainer = webreq2.CookieContainer;
HttpWebResponse resp3 = (HttpWebResponse)webreq3.GetResponse();
//webBrowser1.ScriptErrorsSuppressed = false;
//RegistryKey RegKey = Registry.CurrentUser.OpenSubKey(#"Software\Microsoft\Internet Explorer\Main", true);
//RegKey.SetValue("Display Inline Images", "yes");
string cookie_string = "";
foreach (Cookie cook in resp3.Cookies)
{
cookie_string += cook.ToString() + ";";
InternetSetCookie("http://www.supremenewyork.com/checkout", cook.Name, cook.Value);
}
webBrowser1.Navigate("http://www.supremenewyork.com/checkout");
}
Edit2: added all the code
First of all: I know this has been asked over 100 times, but most of these questions were eigher caused by timeout problems, by incorrect Url or by foregetting to close a stream (and belive me, I tried ALL the samples and none of them worked).
So, now to my question: in my Windows Phone app I'm using the HttpWebRequest to POST some data to a php web service. That service should then save the data in some directories, but to simplify it, at the moment, it only echos "hello".
But when I use the following code, I always get a 404 complete with an apache 404 html document. Therefor I think I can exclude the possibility of a timeout. It seems like the request reaches the server, but for some reason, a 404 is returned. But what really makes me be surprised is, if I use a get request, everything works fine. So here is my code:
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.CreateHttp(server + "getfeaturedpicture.php?randomparameter="+ Environment.TickCount);
webRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0";
webRequest.Method = "POST";
webRequest.ContentType = "text/plain; charset=utf-8";
StreamWriter writer = new StreamWriter(await Task.Factory.FromAsync<Stream>(webRequest.BeginGetRequestStream, webRequest.EndGetRequestStream, null));
writer.Write(Encoding.UTF8.GetBytes("filter=" + Uri.EscapeDataString(filterML)));
writer.Close();
webRequest.BeginGetResponse(new AsyncCallback((res) =>
{
string strg = getResponseString(res);
Stator.mainPage.Dispatcher.BeginInvoke(() => { MessageBox.Show(strg); });
}), webRequest);
Although I don't think this is the reason, here's the source of getResponseString:
public static string getResponseString(IAsyncResult asyncResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asyncResult.AsyncState;
HttpWebResponse webResponse;
try
{
webResponse = (HttpWebResponse)webRequest.EndGetResponse(asyncResult);
}
catch (WebException ex)
{
webResponse = ex.Response as HttpWebResponse;
}
MemoryStream tempStream = new MemoryStream();
webResponse.GetResponseStream().CopyTo(tempStream);
tempStream.Position = 0;
webResponse.Close();
return new StreamReader(tempStream).ReadToEnd();
}
This is tested code work fine in Post method with some body. May this gives you an idea.
public void testSend()
{
try
{
string url = "abc.com";
string str = "test";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "text/plain; charset=utf-8";
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)
{
}
}
I would suggest you to use RestSharp for your POST requests in windows phone. I am making an app for a startup and i faced lots of problems while using a similar code as yours. heres an example of a post request using RestSharp. You see, instead of using 3 functions it can be done in a more concise form. Also the response can be handled efficiently. You can get RestSharp from Nuget.
RestRequest request = new RestRequest("your url", Method.POST);
request.AddParameter("key", value);
RestClient restClient = new RestClient();
restClient.ExecuteAsync(request, (response) =>
{
if (response.StatusCode == HttpStatusCode.OK)
{
StoryBoard2.Begin();
string result = response.Content;
if (result.Equals("success"))
message.Text = "Review submitted successfully!";
else
message.Text = "Review could not be submitted.";
indicator.IsRunning = false;
}
else
{
StoryBoard2.Begin();
message.Text = "Review could not be submitted.";
}
});
It turned out the problem was on the server-side: it tried it on the server of a friend and it worked fine, there. I'll contact the support of the hoster and provide details as soon as I get a response.
Okay I tried asking this question yesterday but i'm not sure if I gave enough info, i got an answer but it hasn't worked for me. Basically what i'm doing is the user opens this windows forms application and logs in. Afterwhich they enter some text into a textbox and click run. At this point the run function is making a webrequest to a server that requires a login (the login that is initially done after they open the program. For some reason its still not seeing that the user is logged in when performing the second request even though the cookies are added too a cookie container. I'm not sure what i'm doing wrong but I will post my code so you can further help me.
This is the function that is performed for the login when the user enters the application.
private void button1_Click(object sender, EventArgs e)
{
string paramaters = "authmethod=on&chkRememberMe=on&login-form-type=pwd&password=" + pw.Text + "&userid=" + uid.Text + "&username=" + uid.Text;
string strResponse;
HttpWebRequest requestLogin = (HttpWebRequest)WebRequest.Create("https://www.url.com/login.form");
requestLogin.Method = "POST";
requestLogin.CookieContainer = cookieJar;
requestLogin.ContentType = "application/x-www-form-urlencoded";
requestLogin.ContentLength = paramaters.Length;
StreamWriter stOut = new StreamWriter(requestLogin.GetRequestStream(), System.Text.Encoding.ASCII);
stOut.Write(paramaters);
stOut.Close();
HttpWebResponse responseLogin = (HttpWebResponse)requestLogin.GetResponse();
StreamReader stIn = new StreamReader(responseLogin.GetResponseStream());
strResponse = stIn.ReadToEnd();
stIn.Close();
//Add cookies to CookieJar (Cookie Container)
foreach (Cookie cookie in responseLogin.Cookies)
{
cookieJar.Add(new Cookie(cookie.Name.Trim(), cookie.Value.Trim(), cookie.Path, cookie.Domain));
richTextBox2.Text += cookie.Name.ToString() + Environment.NewLine + cookie.Value.ToString() + Environment.NewLine + cookie.Path.ToString() + Environment.NewLine + cookie.Domain.ToString();
}
if (strResponse.Contains("Log On Successful") || strResponse.Contains("already has a webseal session"))
{
foreach (Control cont in this.Controls)
{
cont.Visible = true;
}
loginPanel.SendToBack();
loginPanel.Visible = false;
}
else
{
MessageBox.Show("Login failed.");
}
}
This is the function that is ran when the user clicks the "run" button to initiate the tests on a consumer account.
private string runTestRequest(Uri url, string parameters)
{
string testResults = string.Empty;
HttpWebRequest runTest = (HttpWebRequest)WebRequest.Create(url);
runTest.CookieContainer = cookieJar;
runTest.Method = "POST";
runTest.ContentType = "application/x-www-form-urlencoded";
StreamWriter stOut = new StreamWriter(runTest.GetRequestStream(), System.Text.Encoding.ASCII);
stOut.Write(parameters);
stOut.Close();
StreamReader stIn = new StreamReader(runTest.GetResponse().GetResponseStream());
testResults = stIn.ReadToEnd();
stIn.Close();
return testResults;
}
And of course this is my cookie container object
public CookieContainer cookieJar = new CookieContainer();
P.S.: The domains of the webrequests are different. First being abc.com 2nd being 123.com The only problem is that the first domain (which is the login) is a global login for internal web applications like 123.com, so how would i use the login session from the 1st domain with the 2nd domain?
Can you please assist in helping me figure out what I am doing wrong.
I found out that what was happening was it was redircting to a subdomain on the same domain as the 2nd (123.com) to use the login. Evidently they had this global login system built on the multiple domains to pass the cookies. The code above DOES work and i do have it working now. Thanks!!
string url = "http://www.ABC/MemberShip/Login.aspx";// HttpContext.Current.Request.Url.AbsoluteUri.ToString().Replace("AutoLogin", "Login");
CookieContainer myCookieContainer = new CookieContainer();
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.CookieContainer = myCookieContainer;
request.Method = "GET";
request.KeepAlive = false;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
System.IO.Stream responseStream = response.GetResponseStream();
System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
string srcString = reader.ReadToEnd();
// get the page ViewState
string viewStateFlag = "id=\"__VIEWSTATE\" value=\"";
int i = srcString.IndexOf(viewStateFlag) + viewStateFlag.Length;
int j = srcString.IndexOf("\"", i);
string viewState = srcString.Substring(i, j - i);
// get page EventValidation
string eventValidationFlag = "id=\"__EVENTVALIDATION\" value=\"";
i = srcString.IndexOf(eventValidationFlag) + eventValidationFlag.Length;
j = srcString.IndexOf("\"", i);
string eventValidation = srcString.Substring(i, j - i);
string submitButton = "LoginButton";
// UserName and Password
string userName = "userid";
string password = "password";
// Convert the text into the url encoding string
viewState = System.Web.HttpUtility.UrlEncode(viewState);
eventValidation = System.Web.HttpUtility.UrlEncode(eventValidation);
submitButton = System.Web.HttpUtility.UrlEncode(submitButton);
// Concat the string data which will be submit
string formatString =
"txtUserName={0}&txtPassword={1}&btnSignIn={2}&__VIEWSTATE={3}&__EVENTVALIDATION={4}";
string postString =
string.Format(formatString, userName, password, submitButton, viewState, eventValidation);
// Convert the submit string data into the byte array
byte[] postData = Encoding.ASCII.GetBytes(postString);
// Set the request parameters
request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
request.Referer = url;
request.KeepAlive = false;
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; CIBA)";
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = myCookieContainer;
System.Net.Cookie ck = new System.Net.Cookie("TestCookie1", "Value of test cookie");
ck.Domain = request.RequestUri.Host;
request.CookieContainer.Add(ck);
request.CookieContainer.Add(response.Cookies);
request.ContentLength = postData.Length;
// Submit the request data
System.IO.Stream outputStream = request.GetRequestStream();
request.AllowAutoRedirect = true;
outputStream.Write(postData, 0, postData.Length);
outputStream.Close();
// Get the return data
response = request.GetResponse() as HttpWebResponse;
responseStream = response.GetResponseStream();
reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
srcString = reader.ReadToEnd();
Response.Write(srcString);
Response.End();