I would like to port a web browser form submittion to a httpwebrequest one.
its pretty simple:
wb.Document.GetElementsByTagName("input")[0].SetAttribute("value", "image.png");
wb.Document.GetElementsByTagName("input")[1].SetAttribute("value", ImageToBase64(p.Image));
wb.Document.GetElementsByTagName("form")[0].InvokeMember("submit");
I have tried the following, but the image file is currupted somehow...
string param = "name=image.jpg&file=" + ImageToBase64(p.Image);
post(param, "urlToPHPfileShown");
public string post(string param, string url)
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
string postArgs = param;
req.Method = "POST";
req.CookieContainer = new CookieContainer();
req.ContentType = #"application/x-www-form-urlencoded";
byte[] buffer = System.Text.ASCIIEncoding.UTF8.GetBytes(postArgs);
req.ContentLength = buffer.Length;
req.AllowAutoRedirect = true;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(buffer, 0, buffer.Length);
reqStream.Close();
}
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
using (Stream respStream = response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(respStream))
{
string s = sr.ReadToEnd();
return s;
}
}
}
EDIT:
I just looked at the post with WireShark.
The one which is working seem to have lots of %2F instead of just / (slash).
So is there maybe a charset problem?
Related
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
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();
I create method in a static class (window phone) :
public void testSend()
{
try
{
string url = "";
string str = "test";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
string Data = "data=" + str;
byte[] postBytes = Encoding.UTF8.GetBytes(Data);
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = postBytes.Length;
Stream requestStream = req.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
Stream resStream = response.GetResponseStream();
var sr = new StreamReader(response.GetResponseStream());
string responseText = sr.ReadToEnd();
}
catch (WebException)
{
}
I'm not sure but it get error on GetRequestStream() and GetResponse because it does not contain in HttpWebRequest.Please help me.
You need to use WebClient or HttpWebRequest.
Exemple with web client =>
public void testSend()
{
string url = "";
string str = "test";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
string Data = "data=" + str;
byte[] postBytes = Encoding.UTF8.GetBytes(Data);
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = postBytes.Length;
Stream requestStream = req.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
Stream resStream = response.GetResponseStream();
var sr = new StreamReader(response.GetResponseStream());
string responseText = sr.ReadToEnd();
WebClient client = new WebClient();
client.UploadStringCompleted += client_UploadStringCompleted;
client.UploadStringAsync(new Uri(url), responseText);
}
void client_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
if (e.Error != null)
{
// error in uploading
}
}
Here's my code for Request and Response.
System.IO.MemoryStream xmlStream = null;
HttpWebRequest HttpReq = (HttpWebRequest)WebRequest.Create(url);
xmlStream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(format));
byte[] buf2 = xmlStream.ToArray();
System.Text.UTF8Encoding UTF8Enc = new System.Text.UTF8Encoding();
string s = UTF8Enc.GetString(buf2);
string sPost = "XMLData=" + System.Web.HttpUtility.UrlDecode(s);
byte[] bPostData = UTF8Enc.GetBytes(sPost);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded";
HttpReq.Timeout = 30000;
request.Method = "POST";
request.KeepAlive = true;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bPostData, 0, bPostData.Length);
requestStream.Close();
}
string responseString = "";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
responseString = sr.ReadToEnd();
}
No part of this code crashes. The "format" string is the one with XML in it. By the end when you try to see what's in the responseString, it's an empty string. I am supposed to see the XML sent back to me from the URL. Is there something missing in this code?
I would recommend a simplification of this messy code:
using (var client = new WebClient())
{
var values = new NameValueCollection
{
{ "XMLData", format }
};
byte[] resultBuffer = client.UploadValues(url, values);
string result = Encoding.UTF8.GetString(resultBuffer);
}
and if you wanted to upload the XML directly in the POST body you shouldn't be using application/x-www-form-urlencoded as content type. You probably should specify the correct content type, like this:
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "text/xml";
var data = Encoding.UTF8.GetBytes(format);
byte[] resultBuffer = client.UploadData(url, data);
string result = Encoding.UTF8.GetString(resultBuffer);
}
I'm using the following code to log into Craigslist, but haven't succeeded yet.
string formParams = string.Format("inputEmailHandle={0}&inputPassword={1}", "must_chd#yahoo.com", "removed");
//string postData = "inputEmailHandle=must_chd#yahoo.com&inputPassword=removed";
string uri = "https://accounts.craigslist.org/";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.KeepAlive = true;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
byte[] postBytes = Encoding.ASCII.GetBytes(formParams);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postBytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
cookyHeader = response.Headers["Set-cookie"];
string pageSource;
string getUrl = "https://post.craigslist.org/del";
WebRequest getRequest = WebRequest.Create(getUrl);
getRequest.Headers.Add("Cookie", cookyHeader);
WebResponse getResponse = getRequest.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
Use WebTest to record your login process, then generate the code. This will help you to understand what is wrong with YOUR code.