WebClient download string is different than WebBrowser View source - c#

I am create a C# 4.0 application to download the webpage content using Web client.
WebClient function
public static string GetDocText(string url)
{
string html = string.Empty;
try
{
using (ConfigurableWebClient client = new ConfigurableWebClient())
{
/* Set timeout for webclient */
client.Timeout = 600000;
/* Build url */
Uri innUri = null;
if (!url.StartsWith("http://"))
url = "http://" + url;
Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out innUri);
try
{
client.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR " + "3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.2; AskTbFXTV5/5.15.4.23821; BRI/2)");
client.Headers.Add("Vary", "Accept-Encoding");
client.Encoding = Encoding.UTF8;
html = client.DownloadString(innUri);
if (html.Contains("Pagina non disponibile"))
{
string str = "site blocked";
str = "";
}
if (string.IsNullOrEmpty(html))
{
return string.Empty;
}
else
{
return html;
}
}
catch (Exception ex)
{
return "";
}
finally
{
client.Dispose();
}
}
}
catch (Exception ex)
{
return "";
}
}
public class ConfigurableWebClient : WebClient
{
public int? Timeout { get; set; }
public int? ConnectionLimit { get; set; }
protected override WebRequest GetWebRequest(Uri address)
{
var baseRequest = base.GetWebRequest(address);
var webRequest = baseRequest as HttpWebRequest;
if (webRequest == null)
return baseRequest;
if (Timeout.HasValue)
webRequest.Timeout = Timeout.Value;
if (ConnectionLimit.HasValue)
webRequest.ServicePoint.ConnectionLimit = ConnectionLimit.Value;
return webRequest;
}
}
I examine the download content in C# Web client it's slightly different than the browser
content. I give the same URL in browser ( Mozilla Firefox ) and my web client function.
the webpage shows the content correctly but my Web client DownloadString is returns another
HTML. Please see my the Web Client response below.
Webclient downloaded html
<!DOCTYPE html>
<head>
<META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">
<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="refresh" content="10; url=/distil_r_captcha.html?Ref=/pgol/4-abbigliamento/3-Roma%20%28RM%29/p-7&distil_RID=A8D2F8B6-B314-11E3-A5E9-E04C5DBA1712" />
<script type="text/javascript" src="/ga.280243267228712.js?PID=6D4E4D1D-7094-375D-A439-0568A6A70836" defer></script><style type="text/css">#d__fFH{position:absolute;top:-5000px;left:-5000px}#d__fF{font-family:serif;font-size:200px;visibility:hidden}#glance7ca96c1b,#hiredf795fe70,#target01a7c05a,#hiredf795fe70{display:none!important}</style></head>
<body>
<div id="distil_ident_block"> </div>
<div id="d__fFH"><OBJECT id="d_dlg" CLASSID="clsid:3050f819-98b5-11cf-bb82-00aa00bdce0b" width="0px" height="0px"></OBJECT><span id="d__fF"></span></div></body>
</html>
My problem is my Webclient function is not returned the actual webpage content.

Some Web Program respond different by HTTP Request Header.
so, if you want to same HTML as web browser's,
then you will send same HTTP Request which of your Web Browser!
how?
Using Firefox Developer tool or Chrome Developer Tool, and Copy The HTTP Request!

In my case WebClient's DownloadData/DownloadFile/DownloadString methods showed different results than when downloading the file from a browser, like Chrome. First I thought it was an encoding problem and looped through all the encodings from Encoding.GetEncodings(), but the output data showed nonsense characters. Then after much searching I ended up here.
I looked at the Response headers in the Chrome browser Network tab as #han058 suggested and it read:
Cache-Control: public, max-age=900
content-disposition: attachment;filename=FILENAME.csv
Content-Encoding: gzip
Content-Length: 29310
Content-Type: text/plain; charset=utf-8
Date: Sat, 04 Jan 2020 20:20:13 GMT
Expires: Sat, 04 Jan 2020 20:35:14 GMT
Last-Modified: Sat, 04 Jan 2020 20:20:14 GMT
Server: Microsoft-IIS/10.0
Vary: *
X-Powered-By: ASP.NET
X-Powered-By: ARR/3.0
X-Powered-By: ASP.NET
So the response was encoded Content-Encoding: gzip. In other words, I had to unzip the file, before I could read it.
using System;
using System.IO;
using System.IO.Compression;
using System.Net;
public class Program
{
static void Main(string[] args)
{
var url = new Uri("http://www.url.com/FILENAME.csv");
var path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
var fileName = "File.csv";
using (WebClient wc = new WebClient())
using (Stream s = File.Create(Path.Combine(path, fileName)))
using (GZipStream gs = new GZipStream(wc.OpenRead(url), CompressionMode.Decompress))
{
//Saves to C:\Users\[YourUser]\Desktop\File.csv
gs.CopyTo(s);
}
}
}

Related

Send File and data with C# error 403. No error with CURL

I'm trying to upload a file and some data with POST request from my C# program to my server, but I receive always error 403.
The post params are
"id" = folder where the file will be saved
"pos" = the name of the file
So, if an user upload file "abc.text" and POST data are id="Mario" pos="first" the file will be saved in /users/Mario/first.txt
I tried to change params id and pos as GET, but I always have error 403
C# response
{StatusCode: 403, ReasonPhrase: 'Forbidden', Version: 1.1,
Content: System.Net.Http.StreamContent,
Headers:{ Vary: Accept-Encoding X-Varnish: 818481486 Age: 0
X-Cache: MISS Transfer-Encoding: chunked Connection: keep-alive
Date: Thu, 18 Apr 2019 14:29:10 GMT Content-Type: text/html;
charset=iso-8859-1}}
My Code:
<!DOCTYPE html>
<html>
<head>
<title>Upload your files</title>
</head>
<body>
<form enctype="multipart/form-data" action="uploader2.php" method="POST">
<p>Upload your file</p>
<input type="file" name="uploaded_file"></input><br />
<input type="input" name="id"></input><br />
<input type="input" name="pos"></input><br />
<input type="submit" value="Upload"></input>
</form>
</body>
</html>
<!-- language: lang-php -->
<?PHP
if(!empty($_FILES['uploaded_file']))
{
$path = "users/".$_POST['id']."/";
if(!is_dir($path))
{
if(!mkdir ($path,0777,true))
echo 'Error creating folder!';
}
$path = $path.$_POST['pos'].".txt";
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $path)) {
echo "Ok";
} else{
echo "Failed!";
}
}
?>
This is my C# code
using (var httpClient = new HttpClient())
{
MultipartFormDataContent multipartContent = new MultipartFormDataContent();
var fp = File.ReadAllBytes("file.txt");
multipartContent.Add(new StringContent("Mario"), "id");
multipartContent.Add(new StringContent("first"), "pos");
multipartContent.Add(new ByteArrayContent(fp, 0, fp.Length), "uploaded_file", "file.txt");
HttpResponseMessage response = await httpClient.PostAsync("http://host.com/uploader2.php", multipartContent);
response.EnsureSuccessStatusCode();
httpClient.Dispose();
string sd = response.Content.ReadAsStringAsync().Result;
}
}
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
Use this in your php script:
header("Access-Control-Allow-Origin: *"); // wildcard allows access to all domains
Access-Control-Allow-Origin is a CORS (Cross-Origin Resource Sharing) header.
When Site A tries to fetch content from Site B, Site B can send an Access-Control-Allow-Origin response header to tell the browser that the content of this page is accessible to certain origins. (An origin is a domain, plus a scheme and port number.) By default, Site B's pages are not accessible to any other origin; using the Access-Control-Allow-Origin header opens a door for cross-origin access by specific requesting origins.

C# WebClient Strange Characters

I am trying to download this webpage using C# WebClient..
Now it works perfectly with python urllib2 but with c# web client it gives these strange characters in the output file..
I have tried using Encoding with webclient class as well but it doesn't work at all..
public static string GetWebURL()
{
string url = "http://bet.hkjc.com";
WebClient webClient = new WebClient();
webClient.Encoding = Encoding.UTF8;
string html = webClient.DownloadString(url);
File.WriteAllText("page.html", html);
}
this is the output with those strange characters
‹âå²Qtñw‰pUðñõQuòñtVPÒÕ×7vÖ×w qÂH˜è*„%æg–dæç%æèë»ú)ÙñrÂ(N.Ê,(Q(©,HµU*I­(ÑÃJ,K„ˆ*Ùq)((â€U*TÆ’e‰E ©y‰I9©ŽÉÉ©ÅÅÎùy%Eù9 ¶i‰9Å©Ö %â„¢i Xâ€h"(É-P°U(ÃÃŒKÉ/×ËÉON¹H/£(5M¯¸4©¸¤HÃ\SlHu°kPËœkP¼Ÿ£¯+PP/L‘ÂËœ4&µÂ?MCI_IS®+%?713Ã/17¨ ɘfd!¸ zJšÚ†P«Sò“KsSóJô &MA V¨ŸKòô’RK‚s2ÜŠ€ªô2‹}òÓóó445¡ÊÃ=­Wâ€Z“˜œ t|zj^jQbN<Ø1z䁚9‰y鶩yJ_ÂP-ˆÔšœchˆe¦‚ µ\H&[×rÙèC’€0ÂJ%à „ ÷‚üüP9Ud¦MÃÃÔÌØÈÖM×ÃÈ25² ÷ô³V·†(ÃŽM-JOM
What should I do to see the html that is being send?
You're looking at a compressed byte stream. You can tell by inspecting the headers of the http response, for example with curl:
curl -X HEAD -i http://bet.hkjc.com/
but the Developer Console of your browser will reveal the same:
HTTP/1.1 200 OK
Cache-Control: public, max-age=120, must-revalidate
Content-Length: 3615
Content-Type: text/html; charset=utf-8
Content-Encoding: gzip
Expires: Wed, 29 Jun 2016 08:01:06 GMT
Vary: Accept-Encoding
Server: Microsoft-IIS/7.0
X-AspNet-Version: 2.0.50727
X-Powered-By: ASP.NET
Date: Wed, 29 Jun 2016 08:00:14 GMT
Via: 1.1 stjbwbwa52
Accept-Ranges: bytes
Notice the Content-Encoding: to say gzip. This means the result you just got is compressed with the gzip algorithm. The standard WebClient can't handle that but with an simple subclass the WebClient can do new tricks:
public class DecompressWebClient:WebClient
{
// moved common logic here
public DecompressWebClient()
{
this.Encoding = Encoding.UTF8;
}
// This is the factory to create the webrequest
protected override WebRequest GetWebRequest(Uri address)
{
// get the default one
var request = base.GetWebRequest(address);
// see if it is a HttpWebRequest
var httpReq = request as HttpWebRequest;
if (httpReq != null)
{
// add extra capabilities, like decompression
httpReq.AutomaticDecompression = DecompressionMethods.GZip;
}
return request;
}
}
On the HttpWebRequest there exists a property AutomaticDecompression that, when set to true, will take care of the decompression for us.
When you put the Subclassed WebClient to use your code will look like:
string url = "http://bet.hkjc.com";
using(WebClient webClient = new DecompressWebClient())
{
string html = webClient.DownloadString(url);
File.WriteAllText("page.html", html);
}
The encoding UTF8 is correct, as you can also see in the header for the Content-Type setting.
The top of the html file will look like this:
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7; IE=EmulateIE10"/>
<meta name="application-name" content="香港賽馬會"/>
<title>香港賽馬會</title>

Video streaming from database

I am trying to make an action to display media from database (ASP.NET MVC4):
var memoryStream = new MemoryStream(mediaContent.File.FileData.Data);
return new FileStreamResult(memoryStream, MimeMapping.GetMimeMapping(mediaContent.File.Filename));
Pictures are displaying fine, but I have problem with videos (.avi) when I am going to link mysite/media/4 in Chrome or Firefox it displays:
<embed width="100%" height="100%" name="plugin" src="http://mysite/media/4" type="video/x-msvideo">
But video is not playing (as it happens if link pointing to real video file), but if I am opening this link in IE it prompts me to download file and when I am opening this file from player it works fine.
Response headers:
Cache-Control:private, s-maxage=0
Content-Length:808680
Content-Type:video/x-msvideo
Date:Wed, 06 Nov 2013 10:03:09 GMT
Server:Microsoft-IIS/7.5
X-AspNet-Version:4.0.30319
X-AspNetMvc-Version:4.0
X-MiniProfiler-Ids:["e305dcdb-79be-4452-94d2-a9999ffaa13a","c0c81d12-8b31-425c-a57b-2ad186c958d5","1f7f3c09-a695-49f1-9203-6b5bf44b837a","fb0d637e-5926-4759-ad6f-f7322403e98c","f08c0392-10d6-4477-b2df-be52ab9a1d64","366d6122-15a5-41b4-840a-607fc6931996","11fd2eb7-efce-47a1-96f8-09fbdb0b1fa0","690e67b7-b1fb-46a3-9aa3-ef6207203f55","a51640ad-f31d-4f12-a807-6ea06ba0ee46","38adc052-9c41-4243-97d2-41dbf3b36093","9d255225-c122-44ef-8021-5b6f9d4dd549","2b249ff3-9e37-43c3-b6ab-b78b26c6d6ce","2bec0b1b-4898-4b14-bf12-cc331e27ecfc","49c72e01-c8d4-495f-af7e-8ffd687e94e9","1c87e454-f90d-49f4-9618-8dfe0d9c0329","2152a9a8-54ae-47d8-b98a-83ac32dbdb0c","9cf93254-9552-4834-826e-df7e8a7d8e73","a2d782e2-96ca-4e9c-b612-9782a37a06ca","e10ecc8a-5811-4cca-b566-3f09e1de3f2c","3769bb15-60f9-43c3-ad6c-285f3fb47112","1996c4aa-9f76-4f33-95fa-3f7f5b3e72f4"]
X-Powered-By:ASP.NET
What I am doing wrong? I want to have a link which I can use in <object> in order to display this video on page.
Update 1:
The response that I am getting if I type url for physical video file doesn't make any sence:
HTTP/1.1 304 Not Modified
Last-Modified: Tue, 05 Nov 2013 17:07:56 GMT
Accept-Ranges: bytes
ETag: "5d50369249dace1:0"
Server: Microsoft-IIS/7.5
X-Powered-By: ASP.NET
Date: Wed, 06 Nov 2013 11:20:32 GMT
But it works and start play video inside browser using intaled VLC player plugin.
Update 2:
I have tried different implementations to return video and tried to put link to src of object
<object id="video-player" class="preview-container" type="video/x-msvideo" src="{link to video}" loop="true" controls="false" autoplay="true"></object>
So in case if link to real video like "localhost/media/some_video.avi"
then it works fine inside object and if going to url directly.
I checked behavior for different implementations
1) return File(memoryStream, MimeMapping.GetMimeMapping(mediaContent.File.Filename), mediaContent.File.Filename);
to url: prompts to download video file;
in object: shows empty plugin;
2) return new FileContentResult(mediaContent.File.FileData.Data, "application/x-vlc-plugin")
to url: shows empty plugin;
in object: shows empty plugin;
3) return new FileContentResult(mediaContent.File.FileData.Data, "video/avi")
to url: prompts to download video file;
in object: shows empty plugin;
Update 3:
I made a HttpHandler:
public void ProcessRequest(HttpContext context)
{
MediaContent mediaContent;
//getting mediaContent
context.Response.Clear();
context.Response.Buffer = true;
context.Response.AppendHeader("Content-Disposition", "inline; filename=" + mediaContent.File.Filename);
context.Response.ContentType = MimeMapping.GetMimeMapping(mediaContent.File.Filename);
context.Response.BinaryWrite(mediaContent.File.FileData.Data);
context.Response.End();
}
And it simply WORKS. Ok. Then I made action with same logic as Handler:
[HttpGet]
public void Media(int id)
{
MediaContent mediaContent;
//getting mediaContent
Response.Clear();
Response.Buffer = true;
Response.AppendHeader("Content-Disposition", "inline; filename=" + mediaContent.File.Filename);
Response.ContentType = MimeMapping.GetMimeMapping(mediaContent.File.Filename);
Response.BinaryWrite(mediaContent.File.FileData.Data);
Response.End();
}
But this action still not working with video and I started to compare response headers.
Handler:
HTTP/1.1 200 OK
Cache-Control: private
Content-Type: video/x-msvideo
Server: Microsoft-IIS/7.5
Content-Disposition: inline; filename=Reebok_App_attract640L.avi
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Wed, 06 Nov 2013 17:02:45 GMT
Content-Length: 808680
Action:
HTTP/1.1 200 OK
Cache-Control: private, s-maxage=0
Content-Type: video/x-msvideo
Transfer-Encoding: chunked
Server: Microsoft-IIS/7.5
X-AspNetMvc-Version: 4.0
Content-Disposition: inline; filename=Reebok_App_attract640L.avi
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Wed, 06 Nov 2013 17:02:47 GMT
To get rid of Transfer-Encoding I have added Content-Length to my action:
Response.AddHeader("Content-Length", mediaContent.File.FileData.Data.Length.ToString());
I couldn't get rid of s-maxage=0, but now headers similar (except s-maxage=0, X-AspNetMvc-Version: 4.0 and header order)
Well, I did my best to mirror your initial code, minus the database, what I have below works fine for me. VS2012, MVC4, IIS Express local, IIS7.5 remote, works on IE10 local, IE10 remote, IE9 remote. The AVI file I used is some random file I found inside my windows\winsxs folder. I am going to suggest you have a client side problem (IE specifically). Maybe something like cookie handling issues (http://mvolo.com/iis-70-forms-authentication-and-embedded-media-players/), IE security zone settings or something else?
By the way height=100% on embed does not work for me, needs to be pixels.
Controller
namespace MvcApplication4.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return new ViewResult();
}
public ActionResult Media(int id)
{
string fn = Server.MapPath("~/App_Data/boxed-delete.avi");
var memoryStream = new MemoryStream(System.IO.File.ReadAllBytes(fn));
return new FileStreamResult(memoryStream, MimeMapping.GetMimeMapping(System.IO.Path.GetFileName(fn)));
}
}
}
View
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<!-- http://localhost:54941/Home/Media/3 -->
<embed width="100%" height="500" name="plugin" src="~/Home/Media/3" type="video/x-msvideo">
</div>
</body>
</html>
You can put file location stored in the database into a byte buffer array and read from the array in chunk instead of reading whole array at once
WebRequest wreq = (HttpWebRequest)WebRequest.Create(url);
using (HttpWebResponse wresp = (HttpWebResponse)wreq.GetResponse())
using (Stream mystream = wresp.GetResponseStream())
{
using (BinaryReader reader = new BinaryReader(mystream))
{
int length = Convert.ToInt32(wresp.ContentLength);
byte[] buffer = new byte[length];
buffer = reader.ReadBytes(length);
Response.Clear();
Response.Buffer = false;
Response.ContentType = "video/mp4";
while(true) {
int bytesRead = myStream.Read(buffer, 0, buffer.Length);
if (bytesRead == 0) break;
Response.OutputStream.Write(buffer, 0, bytesRead);
}
Response.End();
}
}
Also you can check out the given url weather it helps,
http://www.devcurry.com/2013/04/play-videos-in-aspnet-mvc-html5-using.html
Thanks

IE8 prompts download json response

I've been trying out the jquery form plugin and it works wonderfully. Oh, except for IE8. It's always ie8.
Anyways, on the success response callback, ie8 prompts me to download the response instead of actually calling the success function.
Here is what my javascript code looks like
$("#form1").ajaxForm({
url: "http://localhost:4887/api/file/POST",
type: "POST",
success: function (data)
{
//response stuff here
}
});
I've tried specifying the datatype for the ajax form, but woe is me, it didn't work
The only thing I am returning from the server is just a string. Once again, IE8 prompts me to download this string instead of just calling the success function. After some research, I understand that I might have to modify the http headers? Could anyone shed some light on this? Or give another way of going about this?
UPDATE
Here is a brief look at the C# controller
public class fileController : ApiController
{
public JsonResult POST()
{
HttpPostedFile file = null;
string encodedString = //do stuff here to get the base64 string
ModelName obj = new ModelName();
obj.characters = encodedString;
JsonResult result = new JsonResult();
result.Data = obj;
result.ContentType = "text/html";
return result;
}
Request Headers...
Accept application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, /
Accept-Language en-US
User-Agent Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3; .NET CLR 1.1.4322)
Content-Type multipart/form-data; boundary=---------------------------7dd3e622907b6
Accept-Encoding gzip, deflate
Proxy-Connection Keep-Alive
Content-Length 300
Response Headers
HTTP/1.1 200 OK
Cache-Control no-cache
Pragma no-cache
Content-Type application/json; charset=utf-8
Expires -1
Server Microsoft-IIS/8.0
X-AspNet-Version 4.0.30319
X-Powered-By ASP.NET
try this:
[HttpPost]
public JsonResult POST()
{
HttpPostedFile file = null; ;
string encodedString = //get the file contents, and get the base64 encoded string
ModelName obj= new ModelName();
obj.characters = encodedString;
return Json(obj, "text/html");
}
Update:
Or change the content-type
Response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
example:
public JsonResult POST()
{
HttpPostedFile file = null; ;
string encodedString = //get the file contents, and get the base64 encoded string
ModelName obj= new ModelName();
obj.characters = encodedString;
Response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
return Json(obj, "text/html");
}

How to login to WebService with REST protocol

I've got pdf with a description of API. I must login into their webservice. Webservice is based on REST protocol. To login into this webservice I have to call url like this:
http://api.webepartners.pl/wydawca/Authorize?login=test&password=pass
I have account and password. When I replace test and pass with my login and psw and past url into webbrowser it looks like is ok. No errors occur.
But I must do it programatically in C#.
In google I've found:
http://developer.yahoo.com/dotnet/howto-rest_cs.html
I try this code:
Uri address = new Uri(#"http://api.webepartners.pl/wydawca/Authorize");
// Create the web request
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
// Set type to POST
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// Create the data we want to send
//string appId = "YahooDemo";
//string context = "Italian sculptors and painters of the renaissance"
// + "favored the Virgin Mary for inspiration";
//string query = "madonna";
string userName = "mylogin";
string passsword = "mypassword";
StringBuilder data = new StringBuilder();
//data.Append("appid=" + HttpUtility.UrlEncode(appId));
//data.Append("&context=" + HttpUtility.UrlEncode(context));
//data.Append("&query=" + HttpUtility.UrlEncode(query));
data.Append("login=" + HttpUtility.UrlEncode(userName));
data.Append("&password=" + HttpUtility.UrlEncode(passsword));
// Create a byte array of the data we want to send
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
// Set the content length in the request headers
request.ContentLength = byteData.Length;
// Write data
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) // error
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
}
And I got error in the line using (HttpWebResponse response = request.GetResponse() as ..
An exception of type 'System.Net.WebException' occurred in System.dll but was not handled in user code
Additional information: The remote server returned an error: (405) Method Not Allowed.
Can anyone help me ?
Thanks
You are sending a POST request with username and password as part of the request body. But it seems that the web service expects a GET service where everything is in the URL of the request.
String uriStr = #"http://api.webepartners.pl/wydawca/Authorize?login="
+ HttpUtility.UrlEncode(userName) + "&password=" + HttpUtility.UrlEncode(passsword);
Uri address = new Uri(uriStr);
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) // error
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
}
.....
.....
GET http://api.webepartners.pl/wydawca/Authorize?from=2012-07-29%2013:47:05 HTTP/1.1
Content-Type: text/xml; encoding='utf-8'
Host: api.webepartners.pl
Cookie: .ASPXAUTH=7521F26EBCE8CE487C6860C5E98248B540E5591BD6AE7EC936ECE29B0912AC49C71837B98D7972ABA9C868F18A0C6FCD1EB38B22BE86DBCCCDF8D56D0440170FECF497FF00A1B5D7B268EF6DF27B2B9DB806291E517654A136EC5617A67182DB3E3ECF0D8ADA6F3927C2F955A92E20B7BF7AE6D7DAE2AED0B0D9A7BD406C2CF4
HTTP/1.1 403 Forbidden
Cache-Control: no-cache
Pragma: no-cache
Content-Type: text/html
Expires: -1
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Sun, 29 Jul 2012 11:47:03 GMT
Content-Length: 1233
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>403 - Forbidden: Access is denied.</title>
<style type="text/css">
<!--
body{margin:0;font-size:.7em;font-family:Verdana, Arial, Helvetica, sans-serif;background:#EEEEEE;}
fieldset{padding:0 15px 10px 15px;}
h1{font-size:2.4em;margin:0;color:#FFF;}
h2{font-size:1.7em;margin:0;color:#CC0000;}
h3{font-size:1.2em;margin:10px 0 0 0;color:#000000;}
#header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-family:"trebuchet MS", Verdana, sans-serif;color:#FFF;
background-color:#555555;}
#content{margin:0 0 0 2%;position:relative;}
.content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;position:relative;}
-->
</style>
</head>
<body>
<div id="header"><h1>Server Error</h1></div>
<div id="content">
<div class="content-container"><fieldset>
<h2>403 - Forbidden: Access is denied.</h2>
<h3>You do not have permission to view this directory or page using the credentials that you supplied.</h3>
</fieldset></div>
</div>
</body>
</html>
That's it?
This url http://api.webepartners.pl/wydawca/Authorize?login=test&password=pass has a query string. Since query string values are not used during a POST, maybe you should try a GET instead? It would make sense that the HTTP verb you are using is incorrect with a 405 error.

Categories