i have list word i need to send all this word on webrequest POST method
like here :
this function to request>
private void RequesteUrl(string word)
{
// try
// {
CookieContainer WeBCookies = new CookieContainer();
HttpWebRequest url = (HttpWebRequest)WebRequest.Create("http://mbc.com/index.php");
url.Method = "POST";
url.UserAgent = "Mozilla/5.0 (Windows NT 10.0; rv:44.0) Gecko/20100101 Firefox/44.0";
url.Referer = "http://mbc.com/index.php?";
var PostData = User.Text + "&password=" + word;
var Data = Encoding.ASCII.GetBytes(PostData);
url.ContentLength = Data.Length;
url.Host = "www.mbc.com";
url.ContentType = "application/x-www-form-urlencoded";
// url.Headers.Add(HttpRequestHeader.Cookie, webBrowser1.Document.Cookie);
url.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
url.KeepAlive = true;
url.Headers.Add("Cookie: "+tryit);
using (var stream = url.GetRequestStream())
{
stream.Write(Data, 0, Data.Length);
}
HttpWebResponse WebResponse = (HttpWebResponse)url.GetResponse();
int status = (int)WebResponse.StatusCode;
Stream ST = WebResponse.GetResponseStream();
StreamReader STreader = new StreamReader(ST);
string RR = STreader.ReadToEnd();
// MessageBox.Show (status.ToString() + " " + word);
// }
// catch (Exception ex)
// {
// MessageBox.Show(ex.Message);
// }
}
and i use this to load :
foreach (string selectword in Lists)
{
RequesteUrl(selectword);
}
but foreach not complete all list , he do to two from list only !
Yes, the reason is that you are not releasing resources after your request is complete. Since HTTP/1.1 only allows two simultaneous connections per server, after two requests you will run out of available connections. That is why it hangs.
You need to close the HttpWebResponse, and also good idea to close the streamreader and stream....
using(HttpWebResponse WebResponse = (HttpWebResponse)url.GetResponse())
{
int status = (int)WebResponse.StatusCode;
using(Stream ST = WebResponse.GetResponseStream())
using(StreamReader STreader = new StreamReader(ST))
string RR = STreader.ReadToEnd();
}
Related
So, basically I am creating a Windows Service that is going to consult a SOAP Service and after that return an item. To find that item, who made the service created 2 "filters". customerFilter and itemFilter.
So, when I create the web request I need to insert thoose 2 parameters.
I have this:
static string date = DateTime.Now.Date.ToString("yyyy_MM_dd");
static string pathLog = "Logs/LogGetSalesLineDiscount/" + date + "LogGetSalesLineDiscount.txt";
public static string[] CallWebService(IOrganizationService service)
{
var action = "http://...";
var url = "http://...";
var request = (HttpWebRequest)WebRequest.Create(url);
var postData = "customerFilter=" + Uri.EscapeDataString("TESTE");
postData += "&itemFilter=" + Uri.EscapeDataString("TESTE");
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "text/xml;charset=\"utf-8\"";
request.Headers.Add("SOAPAction", action);
request.ContentLength = data.Length;
request.Accept = "text/xml";
request.Credentials = new NetworkCredential("...", "...");
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
using (System.IO.StreamWriter file = new System.IO.StreamWriter(AppDomain.CurrentDomain.BaseDirectory + pathLog, true))
{
file.WriteLine(responseString);
}
return null;
}
}
If I have that, it will return an error 500. I donĀ“t know why.
If I remove the action, it will return something about all the actions in the service...
Please help me, I dont know what to do....
In my C# Winform application I'm trying to send form post data to a web page of Instagram:
try
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://www.instagram.com/create/configure/");
req.Method = "POST";
if (req.CookieContainer == null)
req.CookieContainer = new CookieContainer();
foreach (System.Net.Cookie cookie in cookies)
{
req.CookieContainer.Add(cookie);
}
String postData = "upload_id=" + upload_id + "&caption=Wow&usertags=&custom_accessibility_caption=&retry_timeout=";
var data = Encoding.UTF8.GetBytes(postData);
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = data.Length;
req.Accept = "*/*";
req.Referer = "https://www.instagram.com/create/details/";
req.Headers["accept-encoding"] = "gzip, deflate, br";
req.Headers["accept-language"] = "en-US,en;q=0.9";
req.Headers["origin"] = "https://www.instagram.com";
req.UserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 10_0_1 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) Version/10.0 Mobile/14A403 Safari/602.1";
req.Headers["x-requested-with"] = "XMLHttpRequest";
req.Headers["x-ig-app-id"] = "1217981644879628";
req.Headers["x-csrftoken"] = csrftoken;
req.Headers["x-instagram-ajax"] = rolloutHash;
using (Stream requestStream = req.GetRequestStream())
{
requestStream.Write(data, 0, data.Length);
requestStream.Close();
}
string source;
using (StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream()))
{
source = reader.ReadToEnd();
}
return source;
}
catch (Exception e)
{
int t = 0;
t++;
}
return "";
But I'm always getting 400 Exception from it. Any idea what can be the problem?
You are probably using an old version of api documentation, currently instagram api allows very limited actions.
check this
https://www.instagram.com/developer/endpoints/
and this
https://developers.facebook.com/docs/instagram-api/reference/media
I try to set request to recognize wav file->to text with Yandex Speech API via desktop app.
Example of request from documentation:
POST /asr_xml?uuid=01ae13cb744628b58fb536d496daa1e6&key=developers-simple- key&topic=maps HTTP/1.1
Content-Type: audio/x-speex
User-Agent: Dalvik/1.2.0 (Linux; U; Android 2.2.2; LG-P990 Build/FRG83G)
Host: asr.yandex.net
Transfer-Encoding: chunked
7d0
...
chunked body
So, i register at developer forum, get api key and write simple code:
public string RecognizeSpeech(byte[] bytes, String uuid, String apiKey, string topic = "queries", string lang = "ru-RU")
{
try
{
var uri = string.Format("https://asr.yandex.net/asr_xml?" +
"uuid={0}" +
"&key={1}" +
"&topic={2}" +
"&lang={3}", uuid, apiKey, topic, lang);
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "audio/x-wav";//"audio/x-pcm;bit=16;rate=16000";
request.ContentLength = bytes.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(bytes, 0, bytes.Length);// exception here
}
var response = request.GetResponse();
var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
return reader.ReadToEnd();
}
catch (Exception ex)
{
...
}
return "";
}
I try to use audio/x-wav or audio/x-pcm;bit=16;rate=16000, but I get error:
Unable to write data to the transport connection: remote host forcibly ripped existing connection.
(use google translate)
byte[] bytes- is:
var audioBytes = File.ReadAllBytes(#"file.wav");
P.S. documentation on Russian language
This gist set POST request to Yandex Speech Cloud.
You need to make valid audio file (i use Freemake) - pcm,16 bit, 16000 hz, mono channel.
Here the solution:
public string PostMethod(byte[] bytes)
{
string postUrl = "https://asr.yandex.net/asr_xml?" +
"uuid=01ae13cb744628b58fb536d496daa1e6&" +
"key="+your_api_key_here+"&" +
"topic=queries";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUrl);
request.Method = "POST";
request.Host = "asr.yandex.net";
request.SendChunked = true;
request.UserAgent = "Oleg";
request.ContentType = "audio/x-pcm;bit=16;rate=16000";
request.ContentLength = bytes.Length;
using (var newStream = request.GetRequestStream())
{
newStream.Write(bytes, 0, bytes.Length);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string responseToString = "";
if (response != null)
{
var strreader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
responseToString = strreader.ReadToEnd();
}
int index = responseToString.IndexOf("<variant confidence=\"1\">");
responseToString = responseToString.Substring(index + 24, responseToString.Length - index - 24);
int index2 = responseToString.IndexOf("</variant>");
responseToString = responseToString.Substring(0, index2);
return responseToString;
}
I've written some code to send and read text from a listener. This runs fine on the 1st and 2nd exchange, but on the 3rd send there's a long delay between calling GetRequestStream() and the actual writing of the data.
I've disposed the outstream on the send side, as well as the stream reader, and the input stream on the read side as recommended here: Does anyone know why I receive an HttpWebRequest Timeout?
And it still hangs on the 3rd attempt to send info. It definitely seems to be hanging at GetRequestStrean() in SendMessage():
public void SendMessage(string message)
{
HttpWebRequest request;
string sendUrl;
sendUrl = "http://" + termIPAddress + ":" + sendPort + "/";
Uri uri = new Uri(sendUrl);
Console.WriteLine("http://" + termIPAddress + ":" + sendPort + "/");
ServicePoint servicePoint = ServicePointManager.FindServicePoint(uri);
servicePoint.BindIPEndPointDelegate = new BindIPEndPoint(BindIPEndPointCallback);
servicePoint.ConnectionLeaseTimeout = 300;
request = (HttpWebRequest)WebRequest.Create(sendUrl);
request.KeepAlive = false;
request.Method = "POST";
request.ProtocolVersion = HttpVersion.Version11;
request.ContentType = "application/x-www-form-urlencoded";
request.Headers.Add("SourceIP", localIPAddress);
request.Headers.Add("MachineName", localName);
requestStarted = true;
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(message);
request.ContentLength = buffer.Length;
try
{
using (Stream output = request.GetRequestStream())
{
output.Write(buffer, 0, buffer.Length);
output.Close();
request = null;
}
}
catch(WebException wE)
{
Console.WriteLine(wE.Message);
}
}
And this is the read portion :
public string GetMessage()
{
Console.WriteLine("Entering actual listener");
string s;
string sourceIP;
NameValueCollection headerList;
HttpListenerContext context = terminalListener.GetContext();
HttpListenerRequest request = context.Request;
headerList = request.Headers;
sourceIP = headerList.GetValues("SourceIP")[0];
termName = headerList.GetValues("MachineName")[0];
termIPAddress = sourceIP;
using (System.IO.Stream body = request.InputStream)
{
System.Text.Encoding encoding = request.ContentEncoding;
using (System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding))
{
s = reader.ReadToEnd();
body.Close();
reader.Close();
}
}
return termName + " : " + s;
}
I also tried to add an IP End Point bind but have to be honest, I don't fully understand this piece of the code:
private IPEndPoint BindIPEndPointCallback(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount)
{
int portNumber = Convert.ToInt32(sendPort);
IPEndPoint IEP = new IPEndPoint(IPAddress.Parse(localIPAddress), 0);
Console.WriteLine(Convert.ToString(IEP));
return IEP;
}
You just forgot to call HttpWebRequest.GetResponse and therefore run out of connection limit.
So, you should change your code as follows:
try
{
using (Stream output = request.GetRequestStream())
output.Write(buffer, 0, buffer.Length);
var response = request.GetResponse() as HttpWebResponse;
//TODO: check response.StatusCode, etc.
}
catch(WebException wE)
{
Console.WriteLine(wE.Message);
}
Also, in some cases you might want to adjust default connection limit:
ServicePointManager.DefaultConnectionLimit
Or use persistent connections:
HttpWebRequest.KeepAlive
I'm trying to get Google APi's access_token using c# and always getting error message invalid_request. There is my code:
var Params = new Dictionary<string, string>();
Params["client_id"] = GoogleApplicationAPI.CLIENT_ID;
Params["client_secret"] = GoogleApplicationAPI.CLIENT_SECRET;
Params["code"] = "4/08Z_Us0a_blkMlXihlixR1579TYu.smV5ucbI8U4VOl05ti8ZT3ZD4CgMcgI";
Params["redirect_uri"] = GoogleApplicationAPI.RETURN_URL;
Params["grant_type"] = "authorization_code";
var RequestData = "";
foreach (var Item in Params)
{
RequestData += Item.Key + "=" + HttpUtility.UrlEncode(Item.Value) + "&";
}
string Url = "https://accounts.google.com/o/oauth2/token";
var request = (HttpWebRequest) WebRequest.Create(Url);
request.Method = HttpMethod.Post.ToString();
request.ContentType = "application/x-www-form-urlencoded";
var SendData = Encoding.UTF8.GetBytes(RequestData);
try
{
request.ContentLength = SendData.Length;
Stream OutputStream = request.GetRequestStream();
OutputStream.Write(SendData, 0, SendData.Length);
} catch {}
try
{
using (var response = (HttpWebResponse) request.GetResponse())
{
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
string JSON = sr.ReadToEnd();
}
} catch {}
I use https://developers.google.com/accounts/docs/OAuth2WebServer#offline
Try removing the call to HttpUtility.UrlEncode on each item in the request data. You shouldn't need to do this as the data is not going into the url it's being POSTed. This is no doubt diluting the information being sent which is resulting in your Invalid Request response.