The underlying connection was closed: The connection was closed unexpectedly - WEB FORMS - c#

I'm project in Web Form, and I am passing an array to a method that will make a post to a URL specifies. However, after I run the project and send the array to the method, it breaks with the error stated in the title.
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://MINHAURL.COM/QUE-RECEBE-O-POST/");
request.Method = "POST";
request.Accept = "application/json";
request.UserAgent = "curl/7.37.0";
request.ContentType = "application/x-www-form-urlencoded";
request.KeepAlive = false;
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string data = "browser=Win7x64-C1|Chrome32|1024x768&url=https://MINHAURL.COM/QUE-RECEBE-O-POST/";
streamWriter.Write(data);
}
WebResponse response = request.GetResponse();
}
private void button1_Click(object sender, EventArgs e)
{
var user = new Usuarios();
var lista = new string[]
{
user.name,
user.dt_nascimento,
user.cidade
};
webBrowser1_DocumentCompleted(lista, null);
}

Related

IIS asp.net C# API Post Method error "'The remote server returned an error: (403) Forbidden.'"

I have via gupshup created a viber bot. I run my WebForm application with IIS server in win 10. I tried to send a message to my viberbot via api post method but c# strangle me.(I tested url and parameters with success)
here is my code :
protected void viber_msg(String viberid, String strmsg)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.gupshup.io/sm/api/bot/mybotname/msg?apikey=mykey");
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "context={'botname':'mybotname','channeltype':'viber','contextid':'viberid','contexttype':'p2p'}&message="+strmsg;
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
viber_msg("viberuserID", "This is a message");
}
The error I am getting is "System.Net.WebException: 'The remote server returned an error: (403) Forbidden.'"
Also tried with POSTMAN and getting "message": "Invalid authentication credentials"
Thnx in advance...
protected void viber_msg(String viberid, String message)
{
var client = new RestClient("https://api.gupshup.io/sm/api/bot/mybot/msg?apikey=myapikey");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("context", "{\"botname\": \"mybot\",\"channeltype\" :\"viber\",\"contextid\": \""+viberid+"\",\"contexttype\": \"p2p\"}");
request.AddParameter("message", message);
IRestResponse response = client.Execute(request);
}
protected void Button1_Click(object sender, EventArgs e)
{
viber_msg("viberid", "message");
}
}
RestSharp Library!!!

HttpWebRequest from a local WCF service

I am doing some testing for a Xamarin Android app with a simple local WCF service to prove my connection code works.
Service:
[OperationContract]
string Ping();
…
public string Ping()
{
return "Pong";
}
Test Code in Xamarin App:
var request = HttpWebRequest.Create(string.Format(#"http://192.168.1.175/_Services/TestService1.svc/Ping"));
request.Credentials = CredentialCache.DefaultCredentials;
request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
request.ContentLength = 0; //pass.Length;
request.Method = "POST";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) //Errors out here
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
var content = reader.ReadToEnd();
Console.Out.WriteLine("Response Body: \r\n {0}", content);
}
}
Error:
The remote server returned an error: (400) Bad Request.
Edit:
When using ServiceReference, the following works:
private void button3_Click(object sender, EventArgs e)
{
ServiceReference1.TestService1Client client = new ServiceReference1.TestService1Client();
string returnString;
returnString = client.Ping();
label1.Text = returnString;
}
Slightly different code still does not work:
private void button4_Click(object sender, EventArgs e)
{
//string serviceUrl = "http://192.168.1.175/_Services/TestService1.svc";
string serviceUrl = "http://localhost/_Services/TestService1.svc";
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(new Uri(serviceUrl + "/Ping"));
httpRequest.Accept = "text/xml";
httpRequest.ContentType = "text/xml";
httpRequest.Method = "POST";
httpRequest.ContentLength = 0;
httpRequest.KeepAlive = false;
using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse()) //400 Bad Request
{
using (Stream stream = httpResponse.GetResponseStream())
{
label1.Text = (new StreamReader(stream)).ReadToEnd();
}
}
}
The answer was rooted in System.ServiceModel.Activation.WebServiceHostFactory
For some reason none of my sources mentioned this during research for using HttpWebRequest.
I found the reference by chance when looking at Android WCF consuming.
https://minafayek.wordpress.com/2013/04/02/consuming-iis-published-restful-wcf-service-from-android-over-wifi/
I got my testing programs working so, I should be able to move forward.

why my http post method is not accepting xml characters?

here is the function:
private void button6_Click(object sender, EventArgs e1)
{
string requestText = string.Format("strXMLData={0}", System.Web.HttpUtility.UrlEncode("<tag1>text</tag1>", e));
string data = "strXMLData=%3c&strXMLFileName=text1.xml"; //Working I am //getting in service mathod <
string data = "strXMLData=%3e&strXMLFileName=text1.xml"; //Working I am getting in service mathod >
//string data = "strXMLData=%3c%3e&strXMLFileName=text1.xml"; //this is also working,I am getting in service mathod
//string data = "strXMLData=%3ct%3e&strXMLFileName=text1.xml"; //this is not working,I am getting error 500, service mathod should revcive either same string or <t>
byte[] dataStream = Encoding.GetEncoding("iso-8859-1").GetBytes(data);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:52995/MyWebService.asmx/ReceiveXMLByContent");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// request.ContentType = "multipart/form-data";
request.ContentLength = dataStream.Length;
Stream newStream = request.GetRequestStream();
newStream.Write(dataStream, 0, dataStream.Length);
newStream.Close();
var reader = new System.IO.StreamReader(request.GetResponse().GetResponseStream());
string dataReturn = reader.ReadToEnd();
}
in above code I have written 3 cases from which two are working and 3rd case
string data = "strXMLData=%3ct%3e&strXMLFileName=text1.xml"; //this is not working,I am getting error 500, service mathod should revcive either same string or <t>
is not working can you explain why it is not passing xml string, I am trying to pass
<tag1>
value
</tag1>
As we cannot pass xml without encoding so I encoded this string using
string requestText = string.Format( System.Web.HttpUtility.UrlEncode("<tag1>text</tag1>", e)); //which returns %3ctag1%3etext%3c%2ftag1%3e
can you explain how to pass xml string..?
without getting error 500
here is web service method
[WebMethod]
public string ReceiveXMLByContent(string strXMLData, string strXMLFileName)
{
string b = System.Web.HttpUtility.UrlDecode(strXMLData);
return "worked";
}
The problem always lies in the following lines
byte[] dataStream = Encoding.GetEncoding("iso-8859-1").GetBytes(data);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:52995/MyWebService.asmx/ReceiveXMLByContent");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentType = "multipart/form-data";
Make sure the request.ContentType is especially proper, like in this syntax:
request.ContentType = "text/xml; charset=\"utf-8\"; action=\"HeaderName\";";
Make sure you use try and catch method like this:
private void button6_Click(object sender, EventArgs e1)
{
string GetHttpPost = string.Empty;
GetHttpPost = CallHTTPPostMethod();
}
public string CallHTTPPostMethod()
{
try
{
//Your code
return YourResponseXMLInStringFormat;
}
catch(Exception wex)
{
string pageContent = new StreamReader(wex.Response.GetResponseStream()).ReadToEnd().ToString();
return pageContent;
}
}

Error 401 attempting to retrieve a web response

Whenever I try a "POST" and attempt to get a response, I get a "401 unauthorized access exception".
The application I am trying to develop is automated Texts to remind me of certain events using the TextNow website.
I have looked around the internet and found that I should use NetworkCredentials to allow me to grab a response, but to no avail. I read around somewhere that because of how HTTP interaction in C# works, that it can't recognize a JSON 401 and retry with an authenticated header. How do I fix this?
namespace HTTPWebTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void snd_Click(object sender, EventArgs e)
{
string pnum = number.Text;
string msg = text.Text;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(new Uri("https://www.textnow.com/api/users/[redacted username]/messages"));
WebResponse response = null;
NetworkCredential netCredential =
new NetworkCredential("[redacted username]", "[redacted password]");
req.Credentials = netCredential;
req.PreAuthenticate = true;
req.Method = "GET";
response = (HttpWebResponse)req.GetResponse(); //error occurs here <<<<<<<<<<<
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13";
req.Referer = "https://www.textnow.com/api/users/[redacted username]/messages";
req.AllowAutoRedirect = true;
req.KeepAlive = true;
req.ContentType = "application/json";
StringBuilder postData = new StringBuilder();
postData.Append("%7B%22contact_value%22%3A%22" + pnum + "%22%2C");
postData.Append("%22contact_type%22%3A2%2C");
postData.Append("%22message%22%3A%22" + msg + "%22%2C");
postData.Append("%22read%22%3A1%2C");
postData.Append("%22message_direction%22%3A2%2C");
postData.Append("%22message_type%22%3A1%2C");
postData.Append("%22date%22%3A%22Sat+Nov+30+2013+13%3A20%3A44+GMT-0800+(Pacific+Standard+Time)%22%2C");
postData.Append("%22from_name%22%3A%22[Redacted]%22%7D");
StreamWriter sw = new StreamWriter(req.GetRequestStream());
sw.Write(postData.ToString());
response = (HttpWebResponse)req.GetResponse();
}
}
}
I had forgotten to include several custom headers that the server required.
For Example:
req.Headers.Add("Access-Control-Request-Headers","accept, origin, x_session, content-type");
req.Headers.Add("Access-Control-Request-Method","POST");
Fiddler:

This is only sending two requests

private async void button2_Click(object sender, EventArgs e)
{
{
var cookie = webBrowser1.Document.Cookie;
foreach (string s in listBox1.Items)
{
var data = "postdata" + s;
var req = WebRequest.Create("example.com") as HttpWebRequest;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = data.Length;
req.Headers["cookie"] = cookie;
using (var sw = new StreamWriter(await req.GetRequestStreamAsync(), Encoding.ASCII))
{
sw.Write(data);
sw.Close();
}
}
listBox1.Items.Clear();
}
}
So my code is supposed to take items from a listbox, and use it send a POST request. It's doing that, but even though I have hundreds of items, it's only running two, then stopping. I'm not getting any errors, so I don't understand what's wrong. I've made sure it's only running twice by putting a messagebox in there.

Categories