I keep receiving the script say "window.location.reload()" when use httpwebrequest - c#

<!--#R--><script>
var k ='c991130d';
var d = new Date();
d.setTime(d.getTime() + (3600*24*365*5*1000));
document.cookie = "p7c=" + k +";
expires=" + d.toGMTString();
setTimeout(function(){
window.location.reload(); },2000);
</script>
please wait....
when I use my code to get a web page I keep getting these, but I can use XMLhttp with VB to get the whole page, it's my code below:
public static string GetPage(string Url)
{
HttpWebRequest WebRequest = (HttpWebRequest)HttpWebRequest.Create(Url);
WebRequest.Timeout = 5000;
WebRequest.AllowAutoRedirect = true;
WebRequest.Headers.Set("Pragma", "no-cache");
try
{
using (HttpWebResponse response = (HttpWebResponse)WebRequest.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(stream, Encoding.GetEncoding("UTF-8")))
{ return sr.ReadToEnd(); }
}
}
}
catch (Exception ex){ return "%ERROR%" + ex.Message; }
}

Related

consuming a soap webservice-getting 500

I have a 500 error when trying to consume a soap WS .
code below :
main function :
public void Main()
{
var action = "XXXXXX";
string result = SendSOAPRequest("http://XXXXXXXX:80/XXXX", action, new Dictionary<string, string>() , false);
}
sendrequest method :
public void Main()
{
var action = "XXXXXX";
string result = SendSOAPRequest("http://XXXXXXXX:80/XXXX", action, new Dictionary<string, string>() , false);
}
public static string SendSOAPRequest(string url, string action,Dictionary<string, string> parameters, bool useSOAP12 = false)
{
try{
XmlDocument soapEnvelopeXml = new XmlDocument();
var xmlStr = (useSOAP12)
? #"XXXXXX";
string parms = string.Join(string.Empty, parameters.Select(kv => String.Format("<{0}>{1}</{0}>", kv.Key, kv.Value)).ToArray());
var s = String.Format(xmlStr, action, new Uri(url).GetLeftPart(UriPartial.Authority) + "/", parms);
soapEnvelopeXml.LoadXml(s);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url + "/" + action));
webRequest.Headers.Add("SOAPAction", url);
webRequest.Headers.Add("XXXXXX", "AG6YUTGV6");
webRequest.ContentType = (useSOAP12) ? "application/soap+xml;charset=\"utf-8\"" : "text/xml;charset=\"utf-8\"";
webRequest.Accept = (useSOAP12) ? "application/soap+xml" : "text/xml";
webRequest.Method = "GET";
string usernamePassword = "username" + ":" + "pass";
usernamePassword = Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword));
CredentialCache mycache = new CredentialCache();
webRequest.Credentials = mycache;
webRequest.Headers.Add("Authorization", "Basic " + usernamePassword);
using (WebResponse response = webRequest.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
XmlTextReader reader = new XmlTextReader(stream);
}
}
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
string result;
using (WebResponse response = webRequest.GetResponse())
{
using (StreamReader rd = new StreamReader(response.GetResponseStream()))
{
result = rd.ReadToEnd();
}
}
return result;
}
catch (WebException ex)
{
string message = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
}
return "";
}

Why this method is called twice and at the first time the return doesn't work?

A flash application uses AMF message format to call the method SyncAddressBook (c#),and in this method ,it calls other two WebApis using HttpWebRequest (post and get ).
But only when calling WebApi (the method SyncAddressBook ), the method can return to flash well, when calling WebApi (the method SyncAddressBook ), the method SyncAddressBook can not return to the one which called it (i didnot write this method here) ,instead, it return itself. and for the second time, the method SyncAddressBook returned with error to flash .
here is the method (I omit something)
public AMFGreetoAddressBookResult SyncAddressBook(AMFGreetoLogin loginArgs, AMFGreetoAddressBook addressBook)
{
var result = new ........
this.PostReceiversGroups(addressBook, accessKey);
this.GetReceivers(accessKey, out receivers);
result.ResultCode = true;
return result;
}
private Boolean PostReceiversGroups(AMFGreetoAddressBook addressBook, string accessKey)
{
Uri theUri = new Uri(athenaSiteUrl + "/api/receivers");
var httpWebRequest = (HttpWebRequest)WebRequest.Create(theUri);
httpWebRequest.KeepAlive = false;
httpWebRequest.Accept = "application/json";
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add(AuthenticationServiceCodeHeaderKey, AddressServiceAccessCode);
httpWebRequest.Headers.Add(uthenticationServiceAccessKeyHeaderKey, AddressServiceAccessKey);
httpWebRequest.Headers.Add(AuthenticationUserAccessKey, accessKey);
httpWebRequest.Host = theUri.Host;
var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(addressBook);
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] bytes = encoding.GetBytes(json);
httpWebRequest.ContentLength = bytes.Length;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
}
try
{
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Account acc = JsonConvert.DeserializeObject<Account>(result);
}
}
catch (Exception e)
{
throw new Exception("住所管理サービスの更新処理でエラーが発生しました。[PostReceiversGroups] :" + e);
}
return true;
}
private Boolean GetReceivers(string accessKey, out AMFGreetoReceiver[] receivers)
{
Uri theUri = new Uri(athenaSiteUrl + "/api/receivers");
var httpWebRequest = (HttpWebRequest)WebRequest.Create(theUri);
httpWebRequest.KeepAlive = false;
httpWebRequest.Accept = "application/json";
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "GET";
httpWebRequest.Headers.Add(AuthenticationServiceCodeHeaderKey, AddressServiceAccessCode);
httpWebRequest.Headers.Add(uthenticationServiceAccessKeyHeaderKey, AddressServiceAccessKey);
httpWebRequest.Headers.Add(AuthenticationUserAccessKey, accessKey);
httpWebRequest.Host = theUri.Host;
receivers = null;
try
{
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
string result = streamReader.ReadToEnd();
var ser = new JavaScriptSerializer();
receivers = ser.Deserialize<AMFGreetoReceiver[]>(result);
streamReader.Close();
httpResponse.Close();
}
}
catch (Exception e)
{
throw new Exception("Receivers取得処理でエラーが発生しました。[GetReceivers] :" + e);
}
return true;
}

How to call specific line in HTTP Get from XML

Right now I get a full dump of this XML...
http://smart-ip.net/geoip-xml/68.5.63.33
What I want my program to do is just call the city and region from that XML.
I'm new to web services so I'm having trouble trying to figure out how to do this, help is much appreciated
Here is my code:
HttpWebRequest myHttpWebRequest = null;
HttpWebResponse myHttpWebResponse = null;
XmlTextReader myXMLReader = null;
try
{
XPathNavigator nav;
XPathDocument docNav;
String weatherURL = "http://smart-ip.net/geoip-xml/" + txtIP.Text;
myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(weatherURL);
myHttpWebRequest.Method = "GET";
myHttpWebRequest.ContentType = "text/xml; encoding='utf-8'";
myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
myXMLReader = new XmlTextReader(myHttpWebResponse.GetResponseStream());
docNav = new XPathDocument(myXMLReader);
nav = docNav.CreateNavigator();
nav.MoveToRoot();
nav.MoveToFirstChild();
do
{
if (nav.NodeType == XPathNodeType.Element)
{
nav.MoveToFirstChild();
do
{
txtIPresults.Text = txtIPresults.Text + nav.Name + " - " + nav.Value + Environment.NewLine; //Display
} while (nav.MoveToNext());
}
} while (nav.MoveToNext());
}
catch (Exception myException)
{
throw new Exception("Error Occurred:", myException);
}
finally
{
myHttpWebRequest = null;
myHttpWebResponse = null;
myXMLReader = null;
}
If I understand correctly you are trying to get the values from the countryName and city elements from the XML response.
This can be done in the following way using the XDocument class from the System.Xml.Linq namespace:
HttpWebRequest myHttpWebRequest = null;
HttpWebResponse myHttpWebResponse = null;
try
{
String weatherURL = "http://smart-ip.net/geoip-xml/" + txtIP.Text;
myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(weatherURL);
myHttpWebRequest.Method = "GET";
myHttpWebRequest.ContentType = "text/xml; encoding='utf-8'";
myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
//---- <Added code> -------
var doc = XDocument.Load(myHttpWebResponse.GetResponseStream());
var geoip = doc.Element("geoip");
var country = geoip.Element("countryName").Value;
var city = geoip.Element("city").Value;
Console.WriteLine(country + " - " + city);
//---- </Added code> -------
}
catch (Exception myException)
{
throw new Exception("Error Occurred:", myException);
}
finally
{
myHttpWebRequest = null;
myHttpWebResponse = null;
}
It's also possible to use the XDocument.Load() method to load the XML response using the url string directly:
String weatherURL = "http://smart-ip.net/geoip-xml/" + txtIP.Text;
var doc = XDocument.Load(weatherURL);
I would do something like this:
try
{
WebClient wc = new WebClient();
wc.Headers.Add();//ADD ALL YOUR HEADERS IF YOU NEED
var xml = wc.DownloadString(string.Format("http://smart-ip.net/geoip-xml/{0}", txtIP.Text));
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
var name = doc.DocumentElement.SelectSingleNode("//countryName").Value;
txtIPresults.Text = name
}
catch (Exception myException)
{
throw new Exception("Error Occurred:", myException);
}
I don´t know for sure if it have more performance than HTTP REQUEST/RESPONSE but the code is very small and easy to maintain.

oauth/token returns empty body

I am encountering a problem getting the access_token in client application using oauth.
The returned response has empty body though in API I can see the response is not empty.
tokenresponse = {
"access_token":"[ACCESSTOKENVALUE]",
"token_type":"bearer",
"expires_in":"1200",
"refresh_token":"[REFRESHTOKENVALUE]",
"scope":"[SCOPEVALUE]"
}
The method from API that returns the token http://api.sample.com/OAuth/Token:
public ActionResult Token()
{
OutgoingWebResponse response =
this.AuthorizationServer.HandleTokenRequest(this.Request);
string tokenresponse = string.Format("Token({0})", response!=null?response.Body:""));
return response.AsActionResult();
}
The client method that requests the token is:
public string GetAuthorizationToken(string code)
{
string Url = ServerPath + "OAuth/Token";
string redirect_uri_encode = UrlEncode(ClientPath);
string param = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code",code, ClientId, ClientSecret, redirect_uri_encode);
HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest;
string result = null;
request.Method = "POST";
request.KeepAlive = true;
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = 10000;
request.Headers.Remove(HttpRequestHeader.Cookie);
var bs = Encoding.UTF8.GetBytes(param);
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
using (WebResponse response = request.GetResponse())
{
var sr = new StreamReader(response.GetResponseStream());
result = sr.ReadToEnd();
sr.Close();
}
if (!string.IsNullOrEmpty(result))
{
TokenData tokendata = JsonConvert.DeserializeObject<TokenData>(result);
return UpdateAuthorizotionFromToken(tokendata);
}
return null;
}
The result variable is empty.
Please let me know if you have any idea what could cause this. Initially I assumed is because of the cookies so I tried to remove them from request.
Thanks in advance.
Dear just create webclient using following code and you will get json info in tokeninfo.I used it and simply its working perfect.
WebClient client = new WebClient();
string postData = "client_id=" + ""
+ "&client_secret=" + ""
+ "&grant_type=password&username=" + "" //your username
+ "&password=" + "";//your password :)
string soundCloudTokenRes = "https://api.soundcloud.com/oauth2/token";
string tokenInfo = client.UploadString(soundCloudTokenRes, postData);
You can then use substring that contains only token from tokeninfo.
To upload tracks on sound cloud.
private void TestSoundCloudupload()
{
System.Net.ServicePointManager.Expect100Continue = false;
var request = WebRequest.Create("https://api.soundcloud.com/tracks") as HttpWebRequest;
//some default headers
request.Accept = "*/*";
request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
request.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
request.Headers.Add("Accept-Language", "en-US,en;q=0.8,ru;q=0.6");
//file array
var files = new UploadFile[] { new UploadFile(Server.MapPath("Downloads//0.mp3"), "track[asset_data]", "application/octet-stream") };
//other form data
var form = new NameValueCollection();
form.Add("track[title]", "Some title");
form.Add("track[sharing]", "public");
form.Add("oauth_token", "");
form.Add("format", "json");
form.Add("Filename", "0.mp3");
form.Add("Upload", "Submit Query");
try
{
using (var response = HttpUploadHelper.Upload(request, files, form))
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
Response.Write(reader.ReadToEnd());
}
}
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}

Why does HttpWebrequest through .Net proxy fail?

I have the following code:
int repeat = 1;
int proxyIndex = 1;
if (listBox1.Items.Count == proxyIndex) //If we're at the end of the proxy list
{
proxyIndex = 0; //Make the selected item the first item in the list
}
try
{
int i = 0;
while (i < listBox1.Items.Count)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(textBox1.Text);
string proxy = listBox1.Items[i].ToString();
string[] proxyArray = proxy.Split(':');
WebProxy proxyz = new WebProxy(proxyArray[0], int.Parse(proxyArray[1]));
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string str = reader.ReadToEnd();
Thread.Sleep(100);
{
repeat++;
continue;
}
}
catch (Exception ex) //Incase some exception happens
{
listBox2.Items.Add("Error:" + ex.Message);
}
I don't understand what I do wrong?
You're not setting Proxy on your HttpWebRequest. (You're creating a WebProxy object, but not using it.) You need to add:
request.Proxy = proxyz;
before calling request.GetResponse().
You also need to fix your use of objects which implement IDisposable. Since they're created in a loop, you cannot delay this - it could be causing any amount of random damage:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
string[] proxyArray = proxyHostAndPort.Split(':');
WebProxy proxyz = new WebProxy(proxyArray[0], int.Parse(proxyArray[1]));
request.Proxy = proxyz;
using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string str = reader.ReadToEnd();
}
}

Categories