Hi i'm getting encoding problems with the code below any ideas?
string url = "http://www.google.com/ig/api?weather=istanbul,TR&hl=tr";
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string retVal = reader.ReadToEnd();
Response.Write(retVal);
}
My Screenshoot is like that;
Thanks for your help!
Google is notorious for checking the useragent HTTP header. Because you're not setting it its encoding everything as ISO-8859-9. The simple solution is to manually set the UserAgent property of the HttpWebRequest. Set it to anything you want, below is a Firefox string (and an extra Using block):
string url = "http://www.google.com/ig/api?weather=istanbul,TR&hl=tr";
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string retVal = reader.ReadToEnd();
Console.WriteLine(retVal);
}
}
Related
When I ran my web application code I got this error on this line.
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()){}
Actually when I ran my url directly on browser.It will give proper o/p but when I ran my url in code. It will give exception.
Here MyCode is :-
string service = "http://api.ean.com/ean-services/rs/hotel/";
string version = "v3/";
string method = "info/";
string hotelId1 = "188603";
int hotelId = Convert.ToInt32(hotelId1);
string otherElemntsStr = "&cid=411931&minorRev=[12]&customerUserAgent=[hotel]&locale=en_US¤cyCode=INR";
string apiKey = "tzyw4x2zspckjayrbjekb397";
string sig = "a6f828b696ae6a9f7c742b34538259b0";
string url = service + version + method + "?&type=xml" + "&apiKey=" + apiKey + "&sig=" + sig + otherElemntsStr + "&hotelId=" + hotelId;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "text/xml";
request.ContentLength = 0;
XmlDocument xmldoc = new XmlDocument();
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
StreamReader responsereader = new StreamReader(response.GetResponseStream());
var responsedata = responsereader.ReadToEnd();
xmldoc = (XmlDocument)JsonConvert.DeserializeXmlNode(responsedata);
xmldoc.Save(#"D:\FlightSearch\myfile.xml");
xmldoc.Load(#"D:\FlightSearch\myfile.xml");
DataSet ds = new DataSet();
ds.ReadXml(Request.PhysicalApplicationPath + "myfile.xml");
GridView1.DataSource = ds.Tables["HotelSummary"];
GridView1.DataBind();
}
The error is providing all you need.
The method POST might not be supported by the api or for this call.
This should work. Try changing the method to "GET"
request.Method = "GET";
In Browser you are sending a GET request to the api. You should do the same in the code as well.
For XML Response:
request.Method = "GET";
request.ContentType = "text/xml; charset=UTF-8";
request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; BOIE9;ENUS)";
request.Accept = "application/xml";
request.ContentLength = 0;
I have a webapp that accepts a messageid and status as a QueryString from an external server. I am migrating the webapp to a new server, but I need the new server to forward the QueryString to the old server in case the old server is still waiting for updates, and until I can get my clients migrated over.
The External website calls my webapp with ?MSGID=12345678&RESPONSE=0
eg:
http://dlrnotify.newserver.com/GetResponse.aspx?MSGID=12345678&RESPONSE=0
I need my code behind GetResponse.aspx to process the message locally, and then forward the request to the old server. eg, calling:
http://dlrnotify.oldserver.com/GetResponse.aspx?MSGID=12345678&RESPONSE=0
I don't really want to redirect the user to the old web server, just to pass the querystring on from my app.
I can get the QueryString by calling Response.QueryString.ToString() I just need to know how to post that to the old server without upsetting anything.
Sorry if this is a dumb question, I don't work with web apps very often and am obviously using the wrong search terms.
You can use HttpWebRequest and HttpWebResponse for this. Below is an example to use thses
Uri uri = new Uri("http://www.microsoft.com/default.aspx");
if(uri.Scheme = Uri.UriSchemeHttp)
{
HttpWebRequest request = HttpWebRequest.Create(uri);
request.Method = WebRequestMethods.Http.Get;
HttpWebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string tmp = reader.ReadToEnd();
response.Close();
Response.Write(tmp);
}
Sample Code on how to Post Data to remote Web Page using HttpWebRequest
Uri uri = new Uri("http://www.amazon.com/exec/obidos/search-handle-form/102-5194535-6807312");
string data = "field-keywords=ASP.NET 2.0";
if (uri.Scheme == Uri.UriSchemeHttp)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = WebRequestMethods.Http.Post;
request.ContentLength = data.Length;
request.ContentType = "application/x-www-form-urlencoded";
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(data);
writer.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string tmp = reader.ReadToEnd();
response.Close();
Response.Write(tmp);
}
After executing your code (process message) on the new server, manually generate a HttpWebRequest which should be to your old server with the same querystring as you already figured out to form.
I have a task which is same as your post. But there is a little more in that.
As we have two web applications, one in asp.net and other in PHP. In both we create user profiles. Now the task is to Create users in Asp.NET application and we need to save the same information in PHP application from Asp.Net app.
I am using the below code for that but it is not wroking, Can you please look at it and let me know what I am missing.
CookieContainer cookies = new CookieContainer();
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(#"http://localhost/admin/config/popup_user_info_brand.php");
request.PreAuthenticate = true;
request.AllowWriteStreamBuffering = true;
request.CookieContainer = cookies; // note this
request.Method = "POST";
string boundary = System.Guid.NewGuid().ToString();
string Username = "admin";
string Password = "admin";
if (!string.IsNullOrEmpty(Username) && !string.IsNullOrEmpty(Password))
{
request.Credentials = new NetworkCredential(Username, Password);
request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
StringBuilder sb = new StringBuilder();
sb.AppendLine("Content-Disposition: form-data; name=\"name\"");
sb.AppendLine("Singh");
sb.AppendLine("Content-Disposition: form-data; name=\"username\"");
sb.AppendLine("Singh123");
sb.AppendLine("Content-Disposition: form-data; name=\"email\"");
sb.AppendLine("a#b.com");
sb.AppendLine("Content-Disposition: form-data; name=\"password\"");
sb.AppendLine("P#ssword");
// This is sent to the Post
byte[] bytes = Encoding.UTF8.GetBytes(sb.ToString());
request.ContentLength = bytes.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Flush();
requestStream.Close();
using (WebResponse response = request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
HttpContext.Current.Response.Write(reader.ReadToEnd());
}
}
}
}
Note:- PHP web site is a 3rd party, we have no access on code.
Thanks,
Ginni.
I'm trying to make web requests programmatically in ASP.NET, using the POST method.
I'd like to send POST parameters with the web request as well. Something like this:
WebRequest req = WebRequest.Create("accounts.craigslist.org/login/pstrdr");
req.Method = "POST";
req.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
//WebRequest.Parameters.add("areaabb","hou");
obviously the commented line does not work. How do I achieve this?
Try like this...
string email = "YOUR EMAIL";
string password = "YOUR PASSWORD";
string URLAuth = "https://accounts.craigslist.org/login";
string postString = string.Format("inputEmailHandle={0}&name={1}&inputPassword={2}", email, password);
const string contentType = "application/x-www-form-urlencoded";
System.Net.ServicePointManager.Expect100Continue = false;
CookieContainer cookies = new CookieContainer();
HttpWebRequest webRequest = WebRequest.Create(URLAuth) as HttpWebRequest;
webRequest.Method = "POST";
webRequest.ContentType = contentType;
webRequest.CookieContainer = cookies;
webRequest.ContentLength = postString.Length;
webRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1";
webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
webRequest.Referer = "https://accounts.craigslist.org";
StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
requestWriter.Write(postString);
requestWriter.Close();
StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
string responseData = responseReader.ReadToEnd();
responseReader.Close();
webRequest.GetResponse().Close();
I send programatically a request to remote server:
string xml = "SomeXML Data";
string url = #"http://someserver.com";
WebRequest request = WebRequest.Create(url);
request.Method = "Post";
request.ContentType = "text/xml";
//The encoding might have to be chaged based on requirement
UTF8Encoding encoder = new UTF8Encoding();
byte[] data = encoder.GetBytes(xml); //postbody is plain string of xml
request.ContentLength = data.Length;
Stream reqStream = request.GetRequestStream();
reqStream.Write(data, 0, data.Length);
reqStream.Close();
System.Net.WebResponse response = request.GetResponse();
System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream());
string str = reader.ReadToEnd();
but this code throws error:
The remote server returned an error: (401) Unauthorized.
I know user/pass to autorize when IE ask me.
Could anyone help me how to send authorized request?
Thanks!
webClient.Credentials = new NetworkCredential("Login", "Password");
Server seems to use Windows Authentication - although I am only guessing. If it is so, add this line:
request.Credentials = CredentialCache.DefaultCredentials;
looks like the server is using windows integrated security?
try something like this
WebRequest req = WebRequest.Create(tokenUri);
req.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
req.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
i am working on asp.net and i wnt to convert following statement in to the c#
Using response As HttpWebResponse = TryCast(request.GetResponse(), HttpWebResponse)
Dim reader As New StreamReader(response.GetResponseStream())
st = reader.ReadToEnd()
End Using
if any one knows it please tell me.
Thank you in advance.
Well, a literal translation would be:
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
st = reader.ReadToEnd();
}
However, if the response isn't an HttpWebResponse that will still fail - just with a NullReferenceException. I'd prefer to cast:
using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
{
StreamReader reader = new StreamReader(response.GetResponseStream());
st = reader.ReadToEnd();
}
Or to be ultra careful that the response will be cleaned up even if it isn't a web response:
using (WebResponse response = request.GetResponse())
{
HttpWebResponse httpResponse = (HttpWebResponse) response;
StreamReader reader = new StreamReader(httpResponse.GetResponseStream());
st = reader.ReadToEnd();
}
... but WebResponse already contains GetResponseStream, so there's no need to cast to HttpWebResponse in the first place, to be honest.
The C# will be something like this:
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
StreamReader reader = new StreamReader(response.GetResponseStream());
st = reader.ReadToEnd();
}
And If I can recognize the code, I think that request.GetResponse() will always be a HttpWebResponse, so you can cast directly as opposed to request.GetResponse() as HttpWebResponse which will return null if the response is not a HttpWebResponse.
using (var response = (HttpWebResponse)request.GetResponse())
{
var reader = new StreamReader(response.GetResponseStream());
st = reader.ReadToEnd();
}
The most direct conversion of TryCast from VB.NET is the as operator in C#. Doing a direct cast will cause an Exception to be thrown rather than response being null:
using(HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
var reader = new StreamReader(response.GetResponseStream());
st = reader.ReadToEnd();
}
Something like this:
using(HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
//Your code here...
}