I am getting the exception error for this code, I have created this form in windows application, the code is to login to the site automatically and downloading the file, and store that in a folder, while debugging I am getting the exception error as “The underlying connection was closed: An unexpected error occurred on a send." and the inner exception is “an existing connection was forcibly closed by the remote host c#”
private void Form1_Load(object sender, EventArgs e)
{
try
{
string formUrl = "https://secure.gmail.com/account/doLogin.html?icmp=HO_LOGIN_BANNER"; // NOTE: This is the URL the form POSTs to, not the URL of the form (you can find this in the "action" attribute of the HTML's form tag
string formParams = string.Format("username={0}&password={1}", "username", "password");
string cookieHeader;
WebRequest req = WebRequest.Create(formUrl);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
WebResponse resp = req.GetResponse();
cookieHeader = resp.Headers["Set-cookie"];
string pageSource;
string getUrl = "https://secure.gmail.com/account/summary.html";
WebRequest getRequest = WebRequest.Create(getUrl);
getRequest.Headers.Add("Cookie", cookieHeader);
WebResponse getResponse = getRequest.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
WebClient Client = new WebClient();
Client.DownloadFile("https://secure.gmail.com.com/account/callActivity/print.csv?lineNumber=16145838755&startDate=MNTH2014-04-24&fragment=true", #"C:\Downloads");
}
catch(Exception ex)
{
throw ex;
}
}
}
}
Related
I am trying to passing C# Web service Parameters to PHP Application but not getting below is my code. Actually I am passing username and password xml format because no buddy should not see that credential while passing.
Below is my C# Web service using asp.net web form button click to redirect PHP application.
[WebMethod]
public string POSTXml(string username, string password)
{
WebRequest req = null;
WebResponse rsp = null;
try
{
StringBuilder strRequest = new StringBuilder();
string url = "http://xyz.in/getuser.php/";
req = WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "text/xml";
StreamWriter writer = new StreamWriter(req.GetRequestStream());
writer.WriteLine(username,password);
writer.Close();
rsp = req.GetResponse();
var sr = new StreamReader(rsp.GetResponseStream());
string responseText = sr.ReadToEnd();
return responseText;
}
catch (Exception e)
{
throw new Exception("There was a problem sending the message");
}
}
Below is my button click code.
protected void Button2_Click(object sender, EventArgs e)
{
localhost.WebService objserv1 = new localhost.WebService();
Label.Text = objserv1.POSTXml("nagapavani", "tech#1234");
}
Actually when user will button click passing some values to web service and through web service want to pass that value to php application. Is there Other way to achieve that requirement. When I am going to button click not going to redirect and taken this code from google.
You could send the data as following. Convert it to a byte array and write it to the request stream:
[WebMethod]
public string POSTXml(string username, string password)
{
WebRequest req = null;
WebResponse rsp = null;
try
{
string data = "user=" + username + "&password=" + password;
string url = "http://xyz.in/getuser.php/";
byte[] buffer = Encoding.ASCII.GetBytes(data);
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
WebReq.Method = "POST";
WebReq.ContentType = "application/x-www-form-urlencoded";
WebReq.ContentLength = buffer.Length;
using (Stream PostData = WebReq.GetRequestStream())
{
PostData.Write(buffer, 0, buffer.Length);
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
using (Stream stream = WebResp.GetResponseStream())
{
using (StreamReader strReader = new StreamReader(stream))
{
return strReader.ReadToEnd();
}
}
WebResp.Close();
}
}
catch (Exception e)
{
throw new Exception("There was a problem sending the message");
}
return String.Empty;
}
I am trying to download pdf from my jasperserver
here is the demo code :
public void Genrate_Report_By_ID(String report_id )
{
String Server_Adress = "http://localhost:8081/jasperserver-pro";
try
{
// Setup WebClient
WebClient httpclient = new WebClient();
//Basic Auth
httpclient.Credentials = new NetworkCredential("superuser", "superuser");
httpclient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Server_Adress+"/rest/resource/organizations/M/Report_By_ID");
request.Method = "GET";
string requestXml = String.Empty;
request.Credentials = httpclient.Credentials;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
requestXml = reader.ReadToEnd();
reader.Close();
dataStream.Close();
}
// Send PUT
string requestAllResult = "";
requestAllResult = httpclient.UploadString(Server_Adress + "/rest/report/organizations/M/Report_By_ID?RUN_OUTPUT_FORMAT=PDF", "PUT", requestXml);
// Get session cookie
string session = httpclient.ResponseHeaders.Get("Set-Cookie");
// Set session cookie
httpclient.Headers.Add("Cookie", session);
// Extract uuid, filename is always report
XmlDocument doc = new System.Xml.XmlDocument();
doc.LoadXml(requestAllResult);
XmlNode node = doc.DocumentElement.SelectSingleNode("uuid");
string uuid = node.InnerText;
//Build GET URL
string reportUrl = Server_Adress + "/rest/report/";
reportUrl += uuid;
reportUrl += "?file=report";
}
catch (Exception ex)
{
throw ex;
}
}
But this Exception occurs .
System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive. ---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
Credential are correct .
i'm having a problem with this simple code which sends a request using provided url and reads html from responce. Looks like it's something with encoding of cyrillic symbols after ?q=, but i can't see why (url was actually obtained from browser address bar, not generated or anything else).
url =
"http://www.avito.ru/nizhniy_novgorod/kvartiry/sdam/na_dlitelnyy_srok?q=%D0%93%D0%B5%D0%BD%D0%B5%D1%80%D0%B0%D0%BB%D0%B0+%D0%98%D0%B2%D0%BB%D0%B8%D0%B5%D0%B2%D0%B0+10%D0%BA1";
string html = "";
try
{
Uri uri = new Uri(url);
WebRequest request = WebRequest.Create(uri);
request.Timeout = 100000;
using (WebResponse responce = request.GetResponse())
{
Stream stream = responce.GetResponseStream();
StreamReader reader = new StreamReader(stream);
html = reader.ReadToEnd();
}
}
catch (Exception e)
{
System.Console.WriteLine(e.Message);
}
Error occures in GetResponce() method. The message is:
The request was aborted: The connection was closed unexpectedly.
You should cast your request and response to HttpWebRequest and HttpWebResponse, respectively.
var url = "http://www.avito.ru/nizhniy_novgorod/kvartiry/sdam/na_dlitelnyy_srok?q=%D0%93%D0%B5%D0%BD%D0%B5%D1%80%D0%B0%D0%BB%D0%B0+%D0%98%D0%B2%D0%BB%D0%B8%D0%B5%D0%B2%D0%B0+10%D0%BA1";
string html = "";
try
{
Uri uri = new Uri(uri);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = 100000;
using (HttpWebResponse responce = (HttpWebResponse)request.GetResponse())
{
Stream stream = responce.GetResponseStream();
StreamReader reader = new StreamReader(stream);
html = reader.ReadToEnd();
Console.WriteLine(html);
}
}
catch (Exception e)
{
System.Console.WriteLine(e.Message);
}
Also, It seems that the url http://www.avito.ru/nizhniy_novgorod/kvartiry/sdam/na_dlitelnyy_srok?q=%D0%93%D0%B5%D0%BD%D0%B5%D1%80%D0%B0%D0%BB%D0%B0+%D0%98%D0%B2%D0%BB%D0%B8%D0%B5%D0%B2%D0%B0+10%D0%BA1 is invalid.
Using Fiddler, the url returns a 404 error.
I am trying to post data from PCL project to remote server. Below is my code:
public async Task<bool> SendToken(string deviceToken, string userId)
{
HttpWebRequest request;
string url = "http://192.168.1.171:91/api/updatePushDeviceToken";
request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "application/json";
request.Method = "POST";
string postData = string.Format("userId={0};token={1}&deviceType={2}", userId, deviceToken, deviceType);
var data = Encoding.UTF8.GetBytes(postData);
try
{
request.BeginGetResponse(new AsyncCallback(FinishRequest), request);
}
catch (Exception e)
{
string m = e.Message;
}
return false;
}
private void FinishRequest(IAsyncResult result)
{
HttpWebResponse response = (result.AsyncState as HttpWebRequest).EndGetResponse(result) as HttpWebResponse;
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(receiveStream);
var responseString = readStream.ReadToEnd();
}
While running above code, below exception was thrown:
System.Net.WebException: The remote server returned an error: (411)
Length Required.
PCL doesn't contain ContentLength property, hence I added Length as below but now I am getting exception as:
try
{
request.Headers[HttpRequestHeader.ContentLength] = "0";
}
catch (Exception e)
{
}
System.ArgumentException: This header must be modified with the
appropiate property. at
System.Net.WebHeaderCollection.CheckRestrictedHeader (System.String
headerName)
Your request is missing of ContentLength property of your post parameters.
var parameters = Encoding.ASCII.GetBytes(qstring);
var request = (HttpWebRequest)HttpWebRequest.Create(url);
request.AllowAutoRedirect = false;
request.ContentType="application/x-www-form-urlencoded";
request.Method = "POST";
request.ContentLength = parameters.Length;
//Send it
var reqStream = request.GetRequestStream();
reqStream.Write(parameters, 0, parameters.Length);
reqStream.Close();
//read it
var response = (HttpWebResponse)request.GetResponse();
var sr = new StreamReader(response.GetResponseStream());
string responseHtml = sr.ReadToEnd().Trim();
And please use querystring format to post data, for example : "userId={0}&token={1}&..."
Help me please.
After sending post query i have webexception "Error getting response stream (ReadDone2): Receive Failure". help get rid of this error. thanks.
piece of code
try
{
string queryContent = string.Format("login={0}&password={1}&mobileDeviceType={2}/",
login, sessionPassword, deviceType);
request = ConnectionHelper.GetHttpWebRequest(loginPageAddress, queryContent);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())//after this line //occurs exception - "Error getting response stream (ReadDone2): Receive Failure"
{
ConnectionHelper.ParseSessionsIdFromCookie(response);
string location = response.Headers["Location"];
if (!string.IsNullOrEmpty(location))
{
string responseUri = Utils.GetUriWithoutQuery(response.ResponseUri.ToString());
string locationUri = Utils.CombineUri(responseUri, location);
result = this.DownloadXml(locationUri);
}
response.Close();
}
}
catch (Exception e)
{
errorCout++;
errorText = e.Message;
}
//Methot GetHttpWebRequest
public static HttpWebRequest GetHttpWebRequest(string uri, string queryContent)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Proxy = new WebProxy(uri);
request.UserAgent = Consts.userAgent;
request.AutomaticDecompression = DecompressionMethods.GZip;
request.AllowWriteStreamBuffering = true;
request.AllowAutoRedirect = false;
string sessionsId = GetSessionsIdForCookie(uri);
if (!string.IsNullOrEmpty(sessionsId))
request.Headers.Add(Consts.headerCookieName, sessionsId);
if (queryContent != string.Empty)
{
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
byte[] SomeBytes = Encoding.UTF8.GetBytes(queryContent);
request.ContentLength = SomeBytes.Length;
using (Stream newStream = request.GetRequestStream())
{
newStream.Write(SomeBytes, 0, SomeBytes.Length);
}
}
else
{
request.Method = "GET";
}
return request;
}
using (Stream newStream = request.GetRequestStream())
{
newStream.Write(SomeBytes, 0, SomeBytes.Length);
//try to add
newStream.Close();
}
In my case the server did not send a response body. After fixing the server, the "Receive Failure" vanished.
So you have two options:
Don't request a response stream, if you can live without it.
Make sure the server sends a response body.
E.g., instead of
self.send_response(200)
self.wfile.close()
the Python server code should be
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write("Thanks!\n")
self.wfile.close()
its not Xamarin or .NET's bug. :wink:
your server side endpoint fails when requesting. :neutral:
check your API endpoint if you own the api or contact support if you are getting API from third party company or service.
why it happens randomly : :wink:
because bug is in your inner if or loop blocks and it happens when it goes through this buggy loop or if.
best regards. :smile: