I am working on a desktop application developed in C# (.NET environment).
This application connects to remote server using HttpWebRequest. If due to any reason my PC is disconnected from the internet and I re-connect it my application always gives request timeout for HttpWebRequest until I restart my whole application and if I again add new thread to my application after network d/c it works fine.
Is there any way to reset my network or anyone can tell me how does it work?
//my code is..
public String request(String add, String post, int time, String reff, int id, int rwtime)
{
try
{
if (rwtime == 0)
{
rwtime = 100000;
}
string result = "";
string location = "";
// Create the web request
HttpWebRequest req = WebRequest.Create(add) as HttpWebRequest;
req.ReadWriteTimeout = rwtime;
req.KeepAlive = true;
req.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
req.Accept = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
req.ContentType = "application/x-www-form-urlencoded";
req.Timeout = time;
req.Referer = reff;
req.AllowAutoRedirect = false;
req.CookieContainer = statictk.cc[id];
req.PreAuthenticate = true;
if (post != "")
{
req.Method = "POST";
string postData = post;
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byte1 = encoding.GetBytes(postData);
// Set the content type of the data being posted.
req.ContentType = "application/x-www-form-urlencoded";
// Set the content length of the string being posted.
req.ContentLength = byte1.Length;
Stream newStream = req.GetRequestStream();
newStream.Write(byte1, 0, byte1.Length);
newStream.Close();
}
else
{
req.Method = "GET";
}
// Get response
try
{
HttpWebResponse response = req.GetResponse() as HttpWebResponse;
// Get the response stream
location = response.GetResponseHeader("Location");
if (location == "")
{
Stream responseStream = response.GetResponseStream();
if (response.ContentEncoding.ToLower().Contains("gzip"))
responseStream = new GZipStream(responseStream, CompressionMode.Decompress);
else if (response.ContentEncoding.ToLower().Contains("deflate"))
responseStream = new DeflateStream(responseStream, CompressionMode.Decompress);
StreamReader reader = new StreamReader(responseStream, Encoding.Default);
// Read the whole contents and return as a string
result = reader.ReadToEnd();
}
else
{
result = location;
}
response.Close();
if (result == "") result = "retry";
return result;
}
catch (Exception e)
{
log.store("errorinresponce", e.Message);
if (statictd.status[id] != "removed")
{
return "retry";
}
else
{
return "error";
}
}
}
catch(Exception f)
{
log.store("Networkerrorretry", f.Message);
if (f.Message == "The operation has timed out")
{
return "retry";
}
string ans = MessageBox.Show("There was a Network Error..Wish to Retry ?\nError msg : "+ f.Message, "Title", MessageBoxButtons.YesNo).ToString();
if (ans == "Yes")
return "retry";
else
{
Invoketk.settxt(id, "Not Ready");
return "error";
}
}
}
It sounds like your application is missing some error handling. A disconnect can happen at any time and your application should be able to handle it. Try to surround the network loop with a try-catch statement, and then catch for the different kinds of exceptions. Depending on what exception was thrown, you can then decide if you reconnect to the server silently or if you want to generate an error message.
Related
My code is as below. But I am getting error. How can I read the url source code in the example.
Error Message 'The remote server returned an error: (403) Forbidden'
CookieContainer cookierJar = new CookieContainer();
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://www.hepsiburada.com/dyson-v11-absolute-extra-kablosuz-supurge-dyson-turkiye-garantili-p-HBV00000W4W6U");
webRequest.AllowAutoRedirect = true;
webRequest.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
webRequest.CookieContainer = cookierJar;
webRequest.UserAgent = "My Thirsty Browser";
int statusCode = 0;
string sourceCode = string.Empty;
try
{
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
statusCode = (int)webResponse.StatusCode;
StreamReader readContent = new StreamReader(webResponse.GetResponseStream());
sourceCode = readContent.ReadToEnd();
webResponse.Close();
webResponse = null;
}
catch (WebException xc)
{
if (xc.Response is HttpWebResponse)
{
HttpWebResponse rs = xc.Response as HttpWebResponse;
StreamReader readContent = new StreamReader(rs.GetResponseStream());
if (readContent != null)
{
sourceCode = readContent.ReadToEnd();
}
statusCode = (int)rs.StatusCode;
}
else
{
statusCode = (int)xc.Status;
sourceCode = xc.Message;
}
}
catch (Exception xc)
{
sourceCode = xc.Message;
}
I get a 403 in IE, I guess you need to be logged in to retrieve the resource. Your browser may have the credentials cached but your app isn't designed to log you in. Or are you logged in to Google in your browser - try logging out and see if you still have access....
I am getting '(400) Bad Request.' when I try complete authenticate against an ALM REST API, the first part (authentication) is successful) and I get the LWSSO_COOKIE_KEY, but site-session always fails with a 400 error code.
What am I doing wrong please... very confused!
// Authentication XML : 0 = User, 1 = Password
private const string AuthenticationXML = #"<alm-authentication>" +
"<user>{0}</user><password>{1}</password></alm-authentication>";
baseRequestURL = settings.QualityCentreURL + "/qcbin/";
Authentication is done first (and is successful) :
string authRequest = baseRequestURL + "authentication-point/alm-authenticate";
HttpWebRequest myauthrequest = (HttpWebRequest)WebRequest.Create(authRequest);
string xml = String.Format(AuthenticationXML, qcSettings.Username, qcSettings.Password);
byte[] Requestbytes = Encoding.UTF8.GetBytes(xml);
myauthrequest.Method = "POST";
myauthrequest.ContentType = "application/xml";
myauthrequest.ContentLength = Requestbytes.Length;
myauthrequest.Accept = "application/xml";
Stream RequestStr = myauthrequest.GetRequestStream();
RequestStr.Write(Requestbytes, 0, Requestbytes.Length);
RequestStr.Close();
HttpWebResponse myauthres = (HttpWebResponse)myauthrequest.GetResponse();
authenticationCookie = myauthres.Headers.Get("Set-Cookie");
The Site-Session code is :
public void GetSiteSession()
{
// Creat the web request fore site-session.
string request = baseRequestURL + "rest/site-session";
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(request);
string xml = String.Empty;
byte[] requestbytes = Encoding.UTF8.GetBytes(xml);
// Update the attributes before sending.
webRequest.Method = "POST";
webRequest.ContentType = "application/xml";
webRequest.Accept = "application/xml";
webRequest.Headers.Set(HttpRequestHeader.Cookie, authenticationCookie);
try
{
Stream requestStream = webRequest.GetRequestStream();
requestStream.Write(requestbytes, 0, requestbytes.Length);
requestStream.Close();
HttpWebResponse webRequestResponse = (HttpWebResponse)webRequest.GetResponse();
Stream responseStream = webRequestResponse.GetResponseStream();
XDocument doc = XDocument.Load(responseStream);
}
catch (System.Net.WebException except)
{
Console.WriteLine(except.Message);
}
}
I have tried cutting ;Path=/;HTTPOnly from LWSSO_COOKIE_KEY as per this question, but to no avail.
The API reference I found(here) seems to be a big vague or, possibly that I haven't understood it... :P
Apologies, it seems that with 12.53 I should have been using 'api/authentication/sign-in'
string requestURL = baseRequestURL + "api/authentication/sign-in";
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestURL);
var credentials = String.Format("{0}:{1}", qcSettings.Username, qcSettings.Password);
request.CookieContainer = authenticationCookieContainer;
request.Headers.Set(HttpRequestHeader.Authorization, "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials)));
var authResponse = request.GetResponse();
errorString = String.Empty;
}
catch (System.Net.WebException except)
{
errorString = except.Message;
return false;
}
errorString = String.Empty;
return true;
}
I am trying to post some data to an EndPoint, resulting in response - illegal characters in path
RootDTO = the DTO structure, I pasted the example XML to this site
So I believe it's not the problem.
Am I doing something wrong?
private Boolean ApiRequest(string order, string path)
{
var t = string.Empty;
var Obj_response = new RootDTO();
byte[] requestData = Encoding.UTF8.GetBytes(order);
HttpWebRequest req = WebRequest.Create(new Uri(path)) as HttpWebRequest;
req.Method = "POST";
req.Accept = "application/xml";
req.ContentType = "application/xml; charset=utf-8";
req.ContentLength = requestData.Length;
using (Stream post = req.GetRequestStream())
{
post.Write(requestData, 0, requestData.Length);
}
try
{
//XmlSerializer serializer = new XmlSerializer(typeof(RootDTO));
using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse)
{
string resJson = string.Empty;
if (resp.StatusCode == HttpStatusCode.OK)
{
var ms = new StreamReader(resp.GetResponseStream(), UTF8Encoding.UTF8);
t = ms.ReadToEnd(); // <-----t contains "illegal characters in path"
return true;
}
else
{ // error occured?
return false;
}
}
}
catch (WebException ex)
{
// error during APIrequest
var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
}
return false;
}
The answer was easy to solve - there were a problem in the XML
the thing that cause the problem was:
<url>
http://www.domain.com
</url>
I changed it to:
<url>http://www.domain.com</url>
that fixed it.
I currently have an employee that is performing manual data entry by taking information from an application which was developed in-house and entering it into a vendor based applications form for class signups. This was not a real issue until official launch of the application, which now we already have 1300+ users with data requiring entry. What I want to achieve is an application which takes the user information we have already collected and automatically submits these forms on the vendor website. A web-service or direct access to the vendors database is out of the question (pricing is astronomical), so I really need this form automation to work. Here is the code I currently have, but don't seem to be getting anywhere with it. Any input would really help.
public static string HttpPost(string uri, string parameters)
{
WebRequest req = WebRequest.Create(uri);
string postData = parameters;
byte[] send = Encoding.Default.GetBytes(postData);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = send.Length;
Stream sout = req.GetRequestStream();
sout.Write(send, 0, send.Length);
sout.Flush();
sout.Close();
WebResponse res = req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
string returnvalue = sr.ReadToEnd();
return null;
//// parameters: name1=value1&name2=value2
//WebRequest webRequest = WebRequest.Create(uri);
////string ProxyString =
//// System.Configuration.ConfigurationManager.AppSettings
//// [GetConfigKey("proxy")];
////webRequest.Proxy = new WebProxy (ProxyString, true);
////Commenting out above required change to App.Config
//webRequest.ContentType = "application/x-www-form-urlencoded";
//webRequest.Method = "POST";
//byte[] bytes = Encoding.ASCII.GetBytes(parameters);
//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)
//{
// Console.WriteLine("HttpPost: Request error");
// Console.Read();
//}
//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)
//{
// Console.WriteLine("HttpPost: Response error");
// Console.Read();
//}
//return null;
} // end HttpPost
SDO REST API - The issue is that when I upload the file, it has no format and it looks like this: 98A9799C-CFB1-423B-A4AD-40609282F861 (2.7 MB) DELETE <--- this file needs to be picture.jpg
The file is simply picture.jpg
public string POST(string URI, string file)
{
NetworkCredential credentials = new NetworkCredential();
credentials.UserName = AppVars.Username;
credentials.Password = AppVars.Password;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URI);
request.Credentials = credentials;
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/x-www-form-urlencoded";
//I have also tried request.ContentType = "image/jpeg"; and ran into the same issue.
byte[] bytes = File.ReadAllBytes(file);
Stream os = null;
try
{
request.ContentLength = bytes.Length;
os = request.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (os != null)
{
os.Close();
}
}
try
{
WebResponse requestResponse = request.GetResponse();
if (requestResponse == null)
{ return null; }
StreamReader sr = new StreamReader(requestResponse.GetResponseStream());
return sr.ReadToEnd().Trim();
}
catch (WebException ex)
{
MessageBox.Show(ex.Message);
}
return null;
}
Problem solved. It was a cache issue. I cleared my browser cache and I was able to view the image online.