help to convert java code to C# - c#

i was trying to get the C# version of the following java code snippet,
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestProperty("Range", "bytes=1024-");
this is what i have so far
WebRequest request = WebRequest.Create(someUri);
request.Headers.Add("Range", "bytes=1024-");
but it is not working,what is the right way for me go?

Presumably your URI is HTTP since Java's HttpURLConnection is designed for a HTTP connection. WebRequest is abstract and can handle multiple protocols. However, by specifiying a HttpWebRequest type, you can access HTTP-specific methods.
The Range header is protected and you should use AddRange to set the property instead of directly adding it to the Header collection.
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(someUri);
request.AddRange("bytes",1024);

You are setting two different things.
A request property is a value passed to the page.
A header property is a header in the HTTP request. Something like setting the HTTP REFERER (sic).

Related

Unable to change the user-agent in Silverlight C#. how I can do it?

I am tring to fetch the html page and want to put my header into request. I tried to do this code.
WebClient client = new WebClient();
WebHeaderCollection coll = new WebHeaderCollection() { { "user-agent", "test" } };
client.DownloadStringCompleted += client_DownloadStringCompleted;
string url = API_URL + pagenum;
client.DownloadStringAsync(new Uri(url));
This code is invalid because http://msdn.microsoft.com/en-us/library/system.net.webheadercollection.aspx don't have add function.
client.Headers["user-agent"] = "xyz"
This is also not work. I tried and got error like user-agent can not be modified. Someone can tell me How to fix it.
I don't see anything that can help me. If this have duplicate here. Point to me that post.
According to the documentation for the Silverlight WebHeaderCollection user-agent is listed as a restricted field that you cannot change, so it appears that there is no way to change it.
Some common headers are considered restricted and are either exposed
directly (such as Content-Type) or protected by the system and cannot
be set or changed in a WebHeaderCollection object. Any attempt to set
one of these restricted headers in the WebHeaderCollection object
associated with a HttpWebRequest object throws an exception. Any
attempt to set one of these restricted headers in the
WebHeaderCollection object associated with a WebClient object will
throw an exception later when attempting to send the WebClient
request.
Many of these restricted headers are set by the web browser that hosts
the Silverlight application.

WebRequest.Create (MSDN example)

I'm trying to create a simple webrequest for a json, i'm attempting to use the example on MSDN.
// Create a new 'Uri' object with the specified string.
Uri myUri =new Uri("http://www.contoso.com");
// Create a new request to the above mentioned URL.
WebRequest myWebRequest= WebRequest.Create(**myUri**);
// Assign the response object of 'WebRequest' to a 'WebResponse' variable.
WebResponse myWebResponse= **myWebRequest**.GetResponse();
I'm getting the following error;
A field initializer cannot reference the non-static field, method, or property
on the objects highlighted. (myUri and myWebRequest) Any idea's?
thanks
This will not work because everything in Silverlight must be Async. They force this because all execution on the main thread like a webrequest would lock the UI. This approach provides a better user experience and is a trade-off to having developers master the use of threads for basic development activities.
See this:
How to use HttpWebRequest (.NET) asynchronously?

Cannot handle redirect from HTTP/HTTPS protocols to other dissimilar ones

Basically, I'm trying to grab an EXE from CNet's Download.com
So i created web parser and so far all is going well.
Here is a sample link pulled directly from their site:
http://dw.com.com/redir?edId=3&siteId=4&oId=3001-20_4-10308491&ontId=20_4&spi=e6323e8d83a8b4374d43d519f1bd6757&lop=txt&tag=idl2&pid=10566981&mfgId=6250549&merId=6250549&pguid=PlvcGQoPjAEAAH5rQL0AAABv&destUrl=ftp%3A%2F%2F202.190.201.108%2Fpub%2Fryl2%2Fclient%2Finstaller-ryl2_v1673.exe
Here is the problem: When you attempt to download, it begins with HTTP, then redirects to an FTP site. I have tried .NET's WebClient and HttpWebRequest Objects, and it looks like Neither can support Redirects.
This Code Fails at GetResponse();
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://dw.com.com/redir");
WebResponse response = req.GetResponse();
Now, I also tried this:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://dw.com.com/redir");
req.AllowAutoRedirect = false;
WebResponse response = req.GetResponse();
string s = new StreamReader(response.GetResponseStream()).ReadToEnd();
And it does not throw the error anymore, however variable s turns out to be an empty string.
I'm at a loss! Can anyone help out?
You can get the value of the "Location" header from the response.headers, and then create a new FtpWebRequest to download that resource.
in your first code snippet you will be redirected to a link using a different protocol (i.e it's no longer Http as in HttpWebRequest) so it fails du to a malformed http response.
In the second part you're no longer redirected and hence you don't receive a FTP response (which is not malform when interpreted as HTTP response).
You need to acquire FTP link,as ferozo wrote you can do this by getting the value of the header "location", and use a FtpWebRequest to access the file

Getting the location from a WebClient on a HTTP 302 Redirect?

I have a URL that returns a HTTP 302 redirect, and I would like to get the URL it redirects to.
The problem is that System.Net.WebClient seems to actually follow it, which is bad. HttpWebRequest seems to do the same.
Is there a way to make a simple HTTP Request and get back the target Location without the WebClient following it?
I'm tempted to do raw socket communication as HTTP is simple enough, but the site uses HTTPS and I don't want to do the Handshaking.
At the end, I don't care which class I use, I just don't want it to follow HTTP 302 Redirects :)
It's pretty easy to do
Let's assume you've created an HttpWebRequest called myRequest
// don't allow redirects, they are allowed by default so we're going to override
myRequest.AllowAutoRedirect = false;
// send the request
HttpWebResponse response = myRequest.GetResponse();
// check the header for a Location value
if( response.Headers["Location"] == null )
{
// null means no redirect
}
else
{
// anything non null means we got a redirect
}
Excuse any compile errors I don't have VS right in front of me, but I've used this in the past to check for redirects.
On HttpWebRequest you can set AllowAutoRedirect to false to handle the redirect yourself.
The HttpWebRequest has a property AllowAutoRedirect which you can set to false (it is always true for WebClient), and then get the Location HTTP header.
Also, for someone who just needs the new location, HttpResponseMessage has a RequestMessage property. Sometimes it can be useful, because WebClient doesn't support changing the AllowAutoRedirect property once it's been set.

C# Equivalent of Snoopy

Snoopy is a PHP class that provides the functionality of a web-browser. Is there anything that does the same in C#? I'm having lots of trouble with handling cookies, etc.
What about Snoopy do you need? There is a WebBrowser Class in C#
You don't specify what about cookies are giving you problems, so this is the best I can do for now for that part:
http://www.google.com/search?q=c%23+cookies
https://stackoverflow.com/search?q=c%23+cookies
The simplest thing would be HttpWebRequest - you create one like this:
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("http://www.example.com/");
//set request properties
//get response
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
And you can then set headers, cookies etc. You could write your own wrapper class to give it an interface similar to Snoopy.

Categories

Resources