Tag Archives: http

C#

Response.Redirect and Thread was being aborted in C#.NET

To prevent error “Thread was being aborted” while Response.Redirect() method execute, use second parameter equals to FALSE:

    Response.Redirect("http://google.com", false);

Also proof,
http://stackoverflow.com/questions/1433448/thread-was-being-aborted
http://programming360.blogspot.com/2009/10/thread-was-being-aborted.html

Read http response correctly!

If you’re using apache http client, method getResponseBodyAsString() set the following:

01 02 2012 17:44:52,484 WARN main org.apache.commons.httpclient.HttpMethodBase - Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.

HttpClient client = new HttpClient();
HttpMethodBase method = new GetMethod("htp://site.com");
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK)
    throw new HttpException(method.getStatusText() + ": " + method.getResponseBodyAsString());
else
{
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    byte[] byteArray = new byte[1024];
    int count = 0;
    while ((count = method.getResponseBodyAsStream().read(byteArray,0,byteArray.length)) > 0)
        outputStream.write(byteArray,0,count);
    return new String(outputStream.toByteArray(),method.getParams().getContentCharset());
}

It’s very importante to use method.getParams().getContentCharset() for correct results! Be aware!

C#

Get file size via HTTP

How to get file size with http-request ?

HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://example.com/");
req.Method = "HEAD";
HttpWebResponse resp = (HttpWebResponse)(req.GetResponse());
int len = resp.ContentLength;