HTTP webrequest for making persistent connection - c#

How do I make the second request within that same connection?
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("String.url");
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
String result = reader.ReadToEnd();
stream.Dispose();
reader.Dispose();

HTTP web request makes a persistent connection..... u can use both "GET" or"POST"
you can increase a connection how much u want(eg 3 to 20 or 50 ...etc)
string webpageContent = "";
byte[] byteArray = Encoding.UTF8.GetBytes("value");
HttpWebRequest webRequest (HttpWebRequest)WebRequest.Create(URL);
webRequest.Method = "POST";
webRequest.KeepAlive = true;
webRequest.Timeout = 120000;
System.Net.ServicePointManager.DefaultConnectionLimit = 3;
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = byteArray.Length;
using (Stream webpageStream = webRequest.GetRequestStream())
{
webpageStream.Write(byteArray, 0, byteArray.Length);
}
using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
{
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
{
webpageContent = reader.ReadToEnd();
}
}

The KeepAlive property on HttpWebRequest is used to persist connections. It defaults to true.
Here's the doc with more details:
https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.keepalive(v=vs.110).aspx

Related

IOException: Unable to read data from the transport connection: The connection was closed

I'm getting this error while trying to posting web service with http:
Unable to read data from the transport connection: The connection was
closed
some similar question: 1
My code:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.KeepAlive = true;
request.ProtocolVersion = HttpVersion.Version10;
request.ServicePoint.ConnectionLimit = 24;
string dataText = items.ToString();
byte[] byteArray = Encoding.UTF8.GetBytes(dataText);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(byteArray, 0, byteArray.Length);
requestStream.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string responseFromServer;
using (var reader = new StreamReader(response.GetResponseStream()))
{
responseFromServer = reader.ReadToEnd();
response.Close();
}
SOLVED:
I've commented the line code of:
//requestStream.Close();
the KeepAlivemake the the http connection to be persistent connection,
it only closing at the end of the connection, the Close() make it throw exception.
https://en.wikipedia.org/wiki/HTTP_persistent_connection

API call going in timeout from windows forms working fine from Postman

I am trying to call API from windows forms its going in timeout. but its working fine from POSTMAN app.
I am using below code for calling web API from windows app.
public string ReadXMLResponse(string strrequestxml, string strTallyServer1)
{
string URL = strTallyServer1;
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(URL);
myHttpWebRequest.Accept = "application/xml";
myHttpWebRequest.ContentType = "application/xml";
myHttpWebRequest.Timeout = 60000;
string method = "POST";
myHttpWebRequest.Method = method;
if (method == "POST")
{
using (var streamWriter = new StreamWriter(myHttpWebRequest.GetRequestStream()))
{
streamWriter.Write(strrequestxml);
streamWriter.Flush();
}
}
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
using (var streamReader = new StreamReader(myHttpWebResponse.GetResponseStream()))
{
var streamRead = streamReader.ReadToEnd().Trim();
return streamRead;
}
return "";
}
I had the same code and the same problem. It was driving me crazy till I found something on one of Microsoft blogs. Tried to google the original page but I couldn't find it.
WebRequest request = WebRequest.Create("URL");
request.Method = "POST";
var postData = string.Format(dataFormnat, Uri.EscapeDataString(data.Serialize()));
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();

HttpWebRequest and Cache Policy

I'm trying to utilize the HttpRequestCachePolicy in a code that download requests from a 3rd party service. My code is currently like this:
protected virtual XmlDocument Send(XmlDocument requestDoc)
{
// Get a SOAP request document that wraps the user request
XmlDocument soapRequestDocument = NewSoapRequestDocument();
InsertRequestDocumentIntoSoapRequestDocument(requestDoc, soapRequestDocument);
Debug.WriteLine(soapRequestDocument.OuterXml);
// Process the request
HttpWebRequest webRequest = HttpWebRequest.Create(URI) as HttpWebRequest;
var policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.CacheIfAvailable);
HttpWebRequest.DefaultCachePolicy = policy;
webRequest.CachePolicy = policy;
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
webRequest.ContentType = "text/xml;charset=\"UTF-8\"";
webRequest.Headers.Add("SOAPAction", string.Format("\"{0}#{1}\"", Service, Method));
byte[] requestBytes = Encoding.UTF8.GetBytes(soapRequestDocument.OuterXml);
webRequest.ContentLength = requestBytes.Length;
Stream requestStream = webRequest.GetRequestStream();
requestStream.Write(requestBytes, 0, requestBytes.Length);
requestStream.Flush();
requestStream.Close();
// Process the response
WebResponse webResponse = webRequest.GetResponse();
Stream responseStream = webResponse.GetResponseStream();
StreamReader responseStreamReader = new StreamReader(responseStream);
// Create SOAP response document
XmlDocument soapResponseDocument = new XmlDocument();
soapResponseDocument.Load(responseStreamReader);
responseStreamReader.Close();
//close
responseStream.Close();
return GetResponseDocument(soapResponseDocument);
}
however, none of the requests are being cached, do I need to use it differently?

The underlying connection was closed: The connection was closed unexpectedly : System.Net.WebException

I have an application written in c#.NET 2.0 Windows app. I am trying to implement web crawler using HttpWebRequest & HttpWebResponse. In this application i am using both http get & post request for a third part web sites. this web site provides user account for its members.
i am trying to login this sites using positing data then entering into my profile page & then trying to make another GETrequest & then make another POST request with post data.
but i am not able to make successfull request .
it through an error
"The server committed a protocol violation. Section=ResponseHeader
Detail=Header name is invalid"
then i set <httpWebRequest useUnsafeHeaderParsing="true" /> in app.config files. after that
it throw an error The underlying connection was closed:
The connection was closed unexpectedly : System.Net.WebException.
anybody can tell me what the reason for showing this error
my code below.
request.CookieContainer = objContainer;
request.KeepAlive = true;
response = (HttpWebResponse)request.GetResponse();
dataStream = response.GetResponseStream();
reader = new StreamReader(dataStream);
strServerResponse = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
//=======================================================================
StringBuilder strLinkBuilder = new StringBuilder();
strLinkBuilder.Append("j_username=username");
strLinkBuilder.Append("&j_password=password");
request = (HttpWebRequest)HttpWebRequest.Create(strBaseURL + "j_security_check");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = strLinkBuilder.ToString();
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
request.KeepAlive = true;
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
for (int i = 0; i < response.Cookies.Count; i++)
{
response.Cookies[i].Path = String.Empty;
}
request.CookieContainer = objContainer;
request.CookieContainer.Add(response.Cookies);
// Get the request stream.
dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
response = (HttpWebResponse)request.GetResponse();
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
reader = new StreamReader(dataStream);
// Read the content.
strServerResponse = reader.ReadToEnd();
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
//-------------------------------------------------------
request = (HttpWebRequest)HttpWebRequest.Create(strBaseURL + "ded/nsdlconsofile.xhtml");
//request.CookieContainer = objContainer;
request.KeepAlive = true;
// request.Method = "POST";
for (int i = 0; i < response.Cookies.Count; i++)
{
response.Cookies[i].Path = String.Empty;
}
request.CookieContainer = objContainer;
request.CookieContainer.Add(response.Cookies);
response = (HttpWebResponse)request.GetResponse();
dataStream = response.GetResponseStream();
reader = new StreamReader(dataStream);
strServerResponse = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
//-------------------------------------------------------
strLinkBuilder = new StringBuilder();
strLinkBuilder.Append("finYr=2012");
strLinkBuilder.Append("&qrtr=3");
strLinkBuilder.Append("&frmType=24Q");
strLinkBuilder.Append("&download_conso=Go");
strLinkBuilder.Append("&requestnsdlconsoForm_SUBMIT=1");
Dictionary<string, string> objNameval = TraceHiddenField(strServerResponse, "");
foreach (KeyValuePair<string, string> pair in objNameval)
{
strLinkBuilder.Append("&" + pair.Key + "=" + pair.Value);
}
request = (HttpWebRequest)HttpWebRequest.Create(strBaseURL + "ded/nsdlconsofile.xhtml");
// Set the Method property of the request to POST.
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
request.KeepAlive = false;
// request.ServicePoint.Expect100Continue = false;
request.UserAgent = "Mozilla/4.0 (compatible;)";
request.ProtocolVersion = HttpVersion.Version10;
// Create POST data and convert it to a byte array.
postData = strLinkBuilder.ToString();
byte[] byteData = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteData.Length;
for (int i = 0; i < response.Cookies.Count; i++)
{
response.Cookies[i].Path = String.Empty;
}
request.CookieContainer = objContainer;
request.CookieContainer.Add( response.Cookies);
// Get the request stream.
dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteData, 0, byteData.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
response = (HttpWebResponse)request.GetResponse();
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
reader = new StreamReader(dataStream);
strServerResponse = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();

get a userID of a facebook user with http request C# WPF

I'm trying to get the userID of a Facebook user, I already have the access_token and I use http request to do it. My simple problem is that : I want the user's id but my program just crash... I use WPF, C# Here is my little call :
var url = string.Format("https://graph.facebook.com/me?access_token=" + token + "&response_type=id");
var req = WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
string postData = "'access_token='" + token;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
var stream = req.GetRequestStream();
stream.Write(byteArray, 0, byteArray.Length);
stream.Close();
WebResponse response = req.GetResponse();
aTextBox.Text = ((HttpWebResponse)response).StatusDescription;
stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
Thanks!
Don't use Web Browser for this! You may use HttpWebRequest for that kind of things:
string url = "https://graph.facebook.com/me?access_token=" + token + "&response_type=id";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
Stream receiveStream = response.GetResponseStream ();
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
string responseData = readStream.ReadToEnd();

Categories