Checks for webserver response - c#

I'm making this folder scanner on a website,
but after 2 successful urls it will crash and i got no idea why.
if (File.Exists(filePath))
{
StreamReader file = null;
file = new StreamReader(filePath);
while ((line = file.ReadLine()) != null)
{
var url = new Uri(txtUrl.Text + line);
try
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.AllowAutoRedirect = true;
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Win32)";
var response = (HttpWebResponse)request.GetResponse();
//Directory.ListView.Items.Add(url.ToString());
MessageBox.Show(url.ToString() + "Success");
}
catch (Exception err)
{
MessageBox.Show(url.ToString() + " fail: " + err.Message);
}
}
if (file != null)
file.Close();
MessageBox.Show("done;");
}

You need to close your HTTPWebResponse object,
response.Close()

Related

Consuming java web service getting error

I am getting error while consuming java web service in my win form application
The error is
You must provide a request body if you set ContentLength>0 or
SendChunked==true. Do this by calling [Begin]GetRequestStream before
[Begin]GetResponse.
My code to consume java service
public byte[] StringToByteArray(string stringData)
{
System.Text.UTF8Encoding Encoding = new System.Text.UTF8Encoding();
return Encoding.GetBytes(stringData);
}
private void button1_Click(object sender, EventArgs e)
{
string DATA = #"<RepositoryType>117</RepositoryType>
<RepositoryCategory>0</RepositoryCategory>
<ModifiedBy>2825</ModifiedBy>
<ReferenceCode>0</ReferenceCode>
<FromDate>2015-10-14T11:50:00</FromDate>
<ToDate>2015-10-14T11:51:00</ToDate>
<RepositoryName>ashok</RepositoryName>
<RepositoryShortName>kumar</RepositoryShortName>
<RepositoryDesc>nothing</RepositoryDesc>
<Fixed>F</Fixed>
<IsValid>true</IsValid>
<lstVisa />
<SortOrder>0</SortOrder>
</Repository>";`
byte[] postdata = null;
HttpWebRequest _WebRequest = null;
HttpWebResponse webresponse = null;
StreamReader ResponseStream = null;
string sReturnVal = string.Empty;
string
serviceAddress="http://172.16.12.21:8888/XML_RESPONSE/rest/test/xmltest/";
try
{
_WebRequest = (HttpWebRequest)WebRequest.Create(serviceAddress + "/" + DATA);
postdata = StringToByteArray(DATA);
if (_WebRequest != null)
{
if (postdata!=null)
{
_WebRequest.Method = "POST";
_WebRequest.ContentType= "text/xml";
_WebRequest.ContentLength = postdata.Length;
_WebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)";
_WebRequest.SendChunked = true;
}
**webresponse = (HttpWebResponse)_WebRequest.GetResponse();**
{
if (webresponse.Headers.Get("Content-Encoding") != null && webresponse.Headers.Get("Content-Encoding").ToLower() == "gzip")
ResponseStream = new StreamReader(new GZipStream(webresponse.GetResponseStream(), CompressionMode.Decompress));
else
{
Encoding enc = System.Text.Encoding.GetEncoding(1252);
ResponseStream = new StreamReader(webresponse.GetResponseStream(), enc);
}
if (ResponseStream != null)
{
XElement Root = XElement.Load(ResponseStream);
sReturnVal = Root.Value;
}
}
}
else
{
throw new Exception("Connection to " + " Service could not be Established.",
new Exception("Please Check whether " +
" Service is running Or Contact your System Administrator."));
}
}
catch(Exception ex)
{
}
}
the highlighted line is getting error.
Please help in this.
You're adding the data to the URL instead of posting it as the request body. Take a look at this question for working code you can use: HTTP POST using web service. With ASP.NET webservices you must set the SOAPAction HTTP header, you can skip this line if your service doesn't require it.

While uploading tracks to soundcloud(422) Unprocessable Entity)

I would like to try upload a mp3 file to my soundcloud account. I have written this code for this job.
WebClient client = new WebClient();
string postData = "client_id=" + "xxxxx"
+ "&client_secret=" + "xxx"
+ "&grant_type=password&username=" + "xxx" //your username
+ "&password=" + "xxx";//your password :)
string soundCloudTokenRes = "https://api.soundcloud.com/oauth2/token";
string tokenInfo = client.UploadString(soundCloudTokenRes, postData);
tokenInfo = tokenInfo.Remove(0, tokenInfo.IndexOf("token\":\"") + 8);
string token = tokenInfo.Remove(tokenInfo.IndexOf("\""));
System.Net.ServicePointManager.Expect100Continue = false;
var request = WebRequest.Create("https://api.soundcloud.com/tracks") as HttpWebRequest;
request.CookieContainer = new CookieContainer();
//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(filePath, "#/" + filePath, "application/octet-stream") };
//other form data
var form = new NameValueCollection();
form.Add("track[title]", "biksad");
form.Add("track[sharing]", "public");
form.Add("oauth_token", token);
form.Add("format", "json");
form.Add("Filename", fileName);
form.Add("Upload", "Submit Query");
string lblInfo;
try
{
using (var response = HttpUploadHelper.Upload(request, files, form))
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
lblInfo = reader.ReadToEnd();
}
}
}
catch (Exception ex)
{
lblInfo = ex.ToString();
}
}
When I debug this code part. I get (422) Unprocessable Entity error in catch block. Why I get this error? How can solve this problem?
Check the Soundcloud documentation:
http://developers.soundcloud.com/docs#errors
422 - "The request looks alright, but one or more of the parameters looks a little screwy. It's possible that you sent data in the wrong format (e.g. an array where we expected a string)."

HttpWebRequest starting to time out after 30ish threads

I am running the following code to start my threads:
stpStartInfo.MaxWorkerThreads = Convert.ToInt32(parserThreadCount.Value);
stpStartInfo.MinWorkerThreads = 1;
_smartThreadPool2 = new Smart.SmartThreadPool(stpStartInfo);
string f = sourceFileName.Text;
int totCount = countLinesInFile(f);
using (StreamReader r = new StreamReader(f))
{
int iia = 0;
string line;
while ((line = r.ReadLine()) != null)
{
if (!string.IsNullOrEmpty(line))
{
_smartThreadPool2.QueueWorkItem(
new Amib.Threading.Func<string, int, int, int>(checkSource),
line, iia, totCount);
iia++;
}
}
}
My threads are doing this HttpWebRequest:
try
{
HttpWebRequest _wReq;
HttpWebResponse _wResp;
System.IO.StreamReader _sr;
System.Text.ASCIIEncoding _enc = new System.Text.ASCIIEncoding();
_wReq = (HttpWebRequest)WebRequest.Create(PAGE_URL);
_wReq.CookieContainer = cookieCont;
_wReq.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
_wReq.ReadWriteTimeout = 10000;
_wReq.Timeout = 10000;
_wReq.ProtocolVersion = HttpVersion.Version10;
_wReq.KeepAlive = false;
_wResp = (HttpWebResponse)_wReq.GetResponse();
_sr = new System.IO.StreamReader(_wResp.GetResponseStream());
html = _sr.ReadToEnd();
_sr.Close();
_cookies = _wReq.CookieContainer;
_wResp.Close();
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null)
{
var resp = (HttpWebResponse)ex.Response;
if (resp.StatusCode == HttpStatusCode.ServiceUnavailable)
{
}
}
}
It works perfectly, but after 30ish threads the requests start to time out..
Any idea how to get around this? :)

Uploading a file to a web service using POST in C#

The problem with this code is that the file, once it is uploaded, is not the correct format. I'm trying to upload a .zip file.
public string HttpPost(string uri, string parameter)
{
WebRequest webRequest = WebRequest.Create(uri);
NetworkCredential credentials = new NetworkCredential("username", "password");
webRequest.Credentials = credentials;
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(parameter);
Stream os = null;
try
{ // send the Post
webRequest.ContentLength = bytes.Length; //Count bytes to send
os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length); //Send it
}
catch (WebException ex)
{
MessageBox.Show(ex.Message, "HttpPost: Request error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (os != null)
{
os.Close();
}
}
try
{ // get the response
WebResponse webResponse = webRequest.GetResponse();
if (webResponse == null)
{ return null; }
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
return sr.ReadToEnd().Trim();
}
catch (WebException ex)
{
MessageBox.Show(ex.Message, "HttpPost: Response error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return null;
}
This example how to upload file in MyBucket
private const string KeyId = "Your KeyId";
private const string AccessKey = "Your AccessKey";
private const string S3Url = "https://s3.amazonaws.com/";
private static void UploadFile()
{
var fileData = File.ReadAllBytes(#"C:\123.zip");
string timeStamp = string.Format("{0:r}", DateTime.UtcNow);
string stringToConvert = "PUT\n" + //Http verb
"\n" + //content-md5
"application/octet-stream\n" + //content-type
"\n" + //date
"x-amz-acl:public-read"+"\n" + //date
"x-amz-date:" + timeStamp + "\n" + //optionall
"/MyBucket/123.zip"; //resource
var ae = new UTF8Encoding();
var signature = new HMACSHA1 {Key = ae.GetBytes(AccessKey)};
var bytes = ae.GetBytes(stringToConvert);
var moreBytes = signature.ComputeHash(bytes);
var encodedCanonical = Convert.ToBase64String(moreBytes);
var url = "https://MyBucket.s3.amazonaws.com/123.zip";
var request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "PUT";
request.Headers["x-amz-date"] = timeStamp;
request.Headers["x-amz-acl"] = "public-read";
request.ContentType = "application/octet-stream";
request.ContentLength = fileData.Length;
request.Headers["Authorization"] = "AWS " + KeyId + ":" + encodedCanonical;
var requestStream = request.GetRequestStream();
requestStream.Write(fileData, 0, fileData.Length);
requestStream.Close();
using (var response = request.GetResponse() as HttpWebResponse)
{
var reader = new StreamReader(response.GetResponseStream());
var data = reader.ReadToEnd();
}
}
Take a look on Amazon S3 REST API

problem in uploading data with HttpWebRequest

Request you to please help me to solve my problem. I am new to web-services and HTTP.
I wrote following code to update data to website. Code run; but I am not able to see my data if uploaded. Here we have facility to see what data is getting uploaded but I am not able to see my data.
// Above URL is not real as I do not want to disclose real URL as of Now
Uri targetUrl = new Uri("http://www.x86map.com/post-embed/ewspost");
HttpWebRequest request = null;
StringBuilder sb = new StringBuilder();
Stream requestStream = null;
try
{
request = (HttpWebRequest)WebRequest.Create(targetUrl);
using (StreamReader inputReader = new StreamReader("C:\\SupportXml.xml"))
{
sb.Append(inputReader.ReadToEnd());
}
String postData = sb.ToString();
byte[] postDataBytes = Encoding.UTF8.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postDataBytes.Length;
request.KeepAlive = true;
request.Accept = "*/*";
request.Headers.Add("Cache-Control", "no-cache");
request.Headers.Add("Accept-Language", "en-us");
request.Headers.Add("Accept-Encoding", "gzip,deflate");
request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8,q=0.66,*;q=0.66");
requestStream = request.GetRequestStream();
requestStream.Write(postDataBytes, 0, postDataBytes.Length);
}
catch (Exception ex)
{
Console.Write(ex.ToString());
}
finally
{
if (null != requestStream)
requestStream.Close();
}
URL I mentioned in Code is not real. Please let me know what is the problem in my code.
Following is the Java code working perfect. I want to convert same code in C#.
// Above URL is not real as I do not want to disclose real URL as of Now
String urlString = "http://www.x86map.com/post-embed/ewspost";
StringBuffer s = new StringBuffer();
try
{
String line = null;
BufferedReader input = new BufferedReader(new FileReader("C:\\SupportXml.xml"));
while ((line = input.readLine()) != null)
{
s.append(line);
s.append(System.getProperty("line.separator"));
}
String xmlDataString = s.toString();
int length = xmlDataString.length();
System.out.println("length " + length);
URL url = new URL(urlString);
System.out.println(url.toString());
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setAllowUserInteraction(false);
connection.setUseCaches(false);
connection.setRequestProperty("Accept", "*/*");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", (String.valueOf(length)));
connection.setRequestProperty("Cache-Control", "no-cache");
connection.setRequestProperty("Accept-Language", "en-us");
connection.setRequestProperty("Accept-Encoding", "gzip,deflate");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8,q=0.66, *;q=0.66");
BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream());
BufferedReader reader = new BufferedReader(new StringReader(xmlDataString));
System.out.println("Proxy Used :" + connection.usingProxy());
int dataRead;
bos.write("XML_string=".getBytes());
while ((dataRead = reader.read()) != -1)
{
bos.write(dataRead);
}
bos.flush();
bos.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String res = null;
while ((res = br.readLine()) != null)
{
}
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
Please help me to resolve this issue.
Thanks and Regards,
map125
You may find it helps to include
requestStream.Flush();
before .Closeing it.
Stream.Flush
I do not see the code that actually gets the response. Is this want is missing?
using (var r = new StreamReader(request.GetResponse().GetResponseStream(), Encoding.UTF8))
result = r.ReadToEnd();

Categories