C# - How to send string to url in window phone? - c#

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
}
}

Related

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();

The remote server returned an error: (403) Forbidden.. in google short url

public string GetShortURL(string longUrl)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.googleapis.com/urlshortener/v1/url?key=My_API_Key");
request.Method = "POST";
request.ContentType = "application/json";
string requestData = string.Format(#"{{""longUrl"": ""{0}""}}", longUrl);
byte[] requestRawData = Encoding.ASCII.GetBytes(requestData);
request.ContentLength = requestRawData.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(requestRawData, 0, requestRawData.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader responseReader = new StreamReader(response.GetResponseStream());
string responseData = responseReader.ReadToEnd();
responseReader.Close();
return responseData;
}
I am trying to create short url by passing my original url string but it is giving an exception

Port webbrowser control, form submit to httpwebrequest?

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?

The stream does not allows seek operations. What are possible solutions?

public static string MakePOSTWebREquest(string url, string contentType, string postData)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
if (!String.IsNullOrEmpty(contentType))
{
req.ContentType = contentType;
}
else
{
req.ContentType = "application/x-www-form-urlencoded";
}
req.Method = "POST";
byte[] pbytes = Encoding.UTF8.GetBytes("list=");
byte[] arr = Encoding.UTF8.GetBytes(postData);
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = arr.Length + pbytes.Length;
Stream stream = req.GetRequestStream(); //error stream does not allows seek operation
stream.Write(pbytes, 0, pbytes.Length);
stream.Write(arr, 0, arr.Length);
stream.Close();
HttpWebResponse webResp = (HttpWebResponse)req.GetResponse();
//Now, we read the response (the string), and output it.
Stream respStream = webResp.GetResponseStream();
GZipStream zStream = new GZipStream(respStream, CompressionMode.Decompress);
StreamReader reader = new StreamReader(zStream);
string respData = reader.ReadToEnd();
return respData;
}
I am getting an exception that says
This stream does not supports seek operation.
What are the possible solutions? This code runs for some time and after some time it gives a error message of The operation has timed out.

How to log in to Craigslist using C#

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.

Categories