I have an ordering website that needs to make a set up request on a supplier site.
For this i am using a WebHanlder (ashx file) to read the setup request in cXML using the HttpContext object which is working fine.
One of the requirements is that we send back a Cookie called "Buyer Cookie" along with a cXML 200 OK response.
The problem I am having is when I create a cookie in the context.Response it is not recieved in the ordering site when I do the response.Output.Write().
I have tried using response.Flush() after the write and this is still not working
How can I send a cookie back to the calling site?
Here is my code:
Ordering site
Stream stream = null;
byte[] bytes = Encoding.ASCII.GetBytes(File.ReadAllText(#"D:\Prototypes\HTTPPost\cXMLFiles\PunchOutSetupRequest.xml"));
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://localhost:45454/PunchOutRequest.ashx");
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
webRequest.ContentLength = bytes.Length;
try
{
stream = webRequest.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
}
catch (Exception)
{
throw;
}
finally
{
if (stream != null)
stream.Close();
}
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(responseStream);
string r = responseReader.ReadToEnd();
var buy = webRequest.CookieContainer;
var buyer = response.Cookies["BuyerCookie"]; // This is always null
Supplier Site
var request = context.Request;
StreamReader reader = new StreamReader(request.InputStream);
string text = reader.ReadToEnd();
POSetup setup = new POSetup();
if (setup.IsSetupRequestValid(text))
{
HttpCookie cookie = new HttpCookie("BuyerCookie", "100");
context.Response.Cookies.Add(cookie);
context.Response.Output.Write(setup.GetOKResponse());
}
Try adding this line:
webRequest.CookieContainer = new CookieContainer();
right after
webRequest.ContentLength = bytes.Length;
Related
Am doing an WEB API .net 4.62 that /Token with username password and grant_type to get access token once its generated i woul like to get it value of access_token.This does not happen but when i take the same code to a windows form aplication I am able to get it what could be wrong. It hangs on using (HttpWebResponse response = (HttpWebResponse)http.GetResponse())
try
{
string myParameters = "username=value1&password=value2&grant_type=password";
string baseAddress = "http://localhost:50128/token";
var http = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress));
http.Accept = "application/x-www-form-urlencoded";
http.ContentType = "application/x-www-form-urlencoded";
http.Method = "POST";
string parsedContent = myParameters;
ASCIIEncoding encoding = new ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(parsedContent);
Stream newStream = http.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();
http.ServicePoint.Expect100Continue = false;
http.ProtocolVersion = HttpVersion.Version11;
http.Timeout = 2000;
using (HttpWebResponse response = (HttpWebResponse)http.GetResponse())
{
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
JObject json = JObject.Parse(content);
var message = json.SelectToken("access_token").ToString();
Console.Write(message);
}
}
catch (Exception ex)
{
//Handle the exceptions that could appear
}
change the using block like this and also convert your function to "async".
using (HttpWebResponse response = (HttpWebResponse)await Task.Factory.FromAsync(http.BeginGetResponse, http.EndGetResponse, null).ConfigureAwait(false))
let me know if it works.
I am attempting to create a console app that sends a WebRequest to a website so that I can get some information back from it in JSON format. Once I build up the request and try to get response I just want to simply print out the data, but when I call httpWebRequest.getResponse() it returns NULL.
I have tried multiple other methods of sending the data to the the url but those are all giving me like 404, or 400 errors, etc. This method at least isn't giving me any error, just a NULL.
Here is a snapshot of the documentation I am using for the API (albeit the docs aren't complete yet):
Here is the console app code that I have right now:
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.remot3.it/apv/v27/user/login");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("developerkey", "***KEY***");
using (var streamWriter = new
StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
email = "***EMAIL***",
password = "***PASSWORD***"
});
Console.WriteLine(json);
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Console.WriteLine(result);
Console.ReadLine();
}
}catch(Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
Console.ReadLine();
}
Expected output is some JSON data, but I am getting a NULL back from getResponse().
Try to serialize the credential in your form and for header send as parameter for this class.
Check below for my code. It is not 100 % fit to your requirement, but atleast it will help to get through your logic.
Here is what I get Json Response from this code. Its work Perfect. Please remember to add timeout option on your webrequest and at the end close the streamreader and stream after completing your task. please check this code.
public static string httpPost(string url, string json)
{
string content = "";
byte[] bs;
if (json != null && json != string.Empty)
{
bs = Encoding.UTF8.GetBytes(json);
}
else
{
bs = Encoding.UTF8.GetBytes(url);
}
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.Method = "POST";
if (json != string.Empty)
req.ContentType = "application/json";
else
req.ContentType = "application/x-www-form-urlencoded";
req.KeepAlive = false;
req.Timeout = 30000;
req.ReadWriteTimeout = 30000;
//req.UserAgent = "test.net";
req.Accept = "application/json";
req.ContentLength = bs.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
reqStream.Flush();
reqStream.Close();
}
using (WebResponse wr = req.GetResponse())
{
Stream s = wr.GetResponseStream();
StreamReader reader = new StreamReader(s, Encoding.UTF8);
content = reader.ReadToEnd();
wr.Close();
s.Close();
reader.Close();
}
return content;
}
I have this hardware from Patlite,
This hardware has an HTTP command control function, for example, if I copy the url "http://192.168.10.1/api/control?alert=101002" to chrome in my computer, it will activate the hardware as needed.
I want to send the command from my code.
I tried this code with no luck:
System.Net.ServicePointManager.Expect100Continue = false;
WebRequest request = WebRequest.Create("http://10.0.22.222/api/control");
request.Method = "post";
request.ContentType = "application/x-www-form-urlencoded";
string postData = "alert=101002";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
WebResponse response = request.GetResponse();
There is a picture from the manual:
Thanks
You need to create a webrequest instance for this.
WebRequest request = WebRequest.Create("http://192.168.10.1/api/control?alert=101002");
WebResponse response = request.GetResponse();
You may need to set some properties as request method and credentials for this to work.
See this:
https://msdn.microsoft.com/en-us/library/456dfw4f(v=vs.100).aspx
public static string Get(string url, Encoding encoding)
{
try
{
var wc = new WebClient { Encoding = encoding };
var readStream = wc.OpenRead(url);
using (var sr = new StreamReader(readStream, encoding))
{
var result = sr.ReadToEnd();
return result;
}
}
catch (Exception e)
{
//throw e;
return e.Message;
}
}
like this code use the url "http://192.168.10.1/api/control?alert=101002" to send get request.Good luck!
I am trying to get cognos report using siteminder token, below is my code.
string cognosUrl = "https://cognos.blah.com";
string reportPath = "/c10/cgi-bin/cognosisapi.dll/rds/reportData/report/"; string reportId = "ildjfsldkf"; //prod
cognosUrl += string.Concat(reportPath, reportId,"?blahblah");
string targetUrl = cognosUrl;
string strFormvalues = string.Concat("TARGET=",targetUrl);
ASCIIEncoding encoder = new ASCIIEncoding();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUrl);
byte[] data = encoder.GetBytes(strFormvalues);
request.AllowAutoRedirect = false;
request.Timeout = 120000;
request.ContentLength = data.Length;
request.ContentType = "text/xml;charset=\"utf-8\"";
request.Method = "POST";
request.Headers.Add(HttpRequestHeader.Cookie,"SMSESSION="+stoken);
request.GetRequestStream().Write(data, 0, data.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string json = reader.ReadToEnd();
byte[] byteArray = Encoding.UTF8.GetBytes(json);
MemoryStream restream = new MemoryStream(byteArray);
using (Stream output = File.OpenWrite(#"c:\\Projects\\Test_"+DateTime.Now.ToString("yyyyMMddHHmmssfff")+".txt"))
using (Stream input = restream)
{
if (input != null) input.CopyTo(output);
}
// var results = serializer.DeserializeObject(json);
reader.Close();
dataStream.Close();
response.Close();
But I am getting response as " DPR-ERR-2101 Your request was invalid.Please contact your administrator."
I am not using C# myself, but a few recommendations while debugging this:
If you are only posting a URL, why not use GET instead of POST?
Try paste the targetURL in your browser, see what happens.
In my setup, when I paste the URL in the browser, I am always redirected before I receive an answer. (to a URL like, /cgi-bin/cognosisapi.dll/rds/sessionOutput/conversationID/i292ED29A62474697AD44306A388F5BBB You are preventing that to happen, that might be an issue)
Hope that helps.
I am using HttpWebRequest to get webpage source code with POST method.
The page needs to be accessed for multiple times with different parameters.
When getting response in the second time in a short period, it always return the same response object to me. After debugging, if the second call is after around 30 seconds, the request can get the correct response object(source code).
public HtmlAgilityPack.HtmlDocument getHtmlData(string url, string cname)
{
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
try
{
HttpRequestCachePolicy policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Default);
HttpWebRequest.DefaultCachePolicy = policy;
HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.KeepAlive = false;
req.Headers[HttpRequestHeader.CacheControl] = "no-cache";
req.Headers[HttpRequestHeader.Pragma] = "no-cache";
req.IfModifiedSince = DateTime.Now;
req.CachePolicy = noCachePolicy;
//add post data
string postData = "cname=" + cname;
byte[] byteArray = Encoding.GetEncoding("shift-jis").GetBytes(postData);
req.ContentLength = byteArray.Length;
using (Stream stream = req.GetRequestStream())
{
stream.Write(byteArray, 0, byteArray.Length);
}
// get response
string data = "";
HttpWebResponse response = req.GetResponse() as HttpWebResponse;
using (var stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("shift-jis"));
data = reader.ReadToEnd();
reader.Close();
}
response.Close();
doc.LoadHtml(data);
//System.Threading.Thread.Sleep(30000);
}
catch(Exception ex)
{
Log.log.Debug(ex.ToString());
}
return doc;
}
Function call block:
getHtmlData(#"http://www.jra.go.jp/JRADB/accessS.html", "pw01sli00/AF");
getHtmlData(#"http://www.jra.go.jp/JRADB/accessS.html", "pw01skl00999999/B3");
getHtmlData(#"http://www.jra.go.jp/JRADB/accessS.html", "pw01skl00201604/E3");
I have stuck with the problem for a whole day. hope someone can give me a clue.
Many thanks!