I am using this code :
public void sendPostData(string url, string data)
{
WebRequest req = WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
byte[] bytes = Encoding.UTF8.GetBytes(data);
req.ContentLength = bytes.Length;
Stream dataStream = req.GetRequestStream();
dataStream.Write(bytes, 0, bytes.Length);
dataStream.Close();
}
PHP for POST processing :
<?php
if(#$_POST['filename'])
{
$data = filter_var($_POST['filename'], FILTER_SANITIZE_STRING);
$f = fopen($data.".txt", "w");
fclose($f);
}
?>
I am calling by this :
sendPostData("http://127.0.0.1/csharptest/index.php", "filename=myvariablehere");
So, all it does is create a file name "myvariablehere" on server instead of storing value in myvariablehere which holds the data.
I Want "myvariablehere" value stored on server.
Please lil help here !
Thanks
Try this code
public static class Upload
{
public static byte[] Post(string uri, NameValueCollection pairs)
{
byte[] response = null;
using (WebClient client = new WebClient())
{
response = client.UploadValues(uri, pairs);
}
return response;
}
}
and then simply call this
var response = Upload.Post("URL", new NameValueCollection() {
{ "fileName", "test" },
});
Related
I have this hardware from Patlite,
This hardware has an HTTP command control function, for example, if I copy the url "http://192.168.10.1/api/control?alert=101002" to chrome in my computer, it will activate the hardware as needed.
I want to send the command from my code.
I tried this code with no luck:
System.Net.ServicePointManager.Expect100Continue = false;
WebRequest request = WebRequest.Create("http://10.0.22.222/api/control");
request.Method = "post";
request.ContentType = "application/x-www-form-urlencoded";
string postData = "alert=101002";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
WebResponse response = request.GetResponse();
There is a picture from the manual:
Thanks
You need to create a webrequest instance for this.
WebRequest request = WebRequest.Create("http://192.168.10.1/api/control?alert=101002");
WebResponse response = request.GetResponse();
You may need to set some properties as request method and credentials for this to work.
See this:
https://msdn.microsoft.com/en-us/library/456dfw4f(v=vs.100).aspx
public static string Get(string url, Encoding encoding)
{
try
{
var wc = new WebClient { Encoding = encoding };
var readStream = wc.OpenRead(url);
using (var sr = new StreamReader(readStream, encoding))
{
var result = sr.ReadToEnd();
return result;
}
}
catch (Exception e)
{
//throw e;
return e.Message;
}
}
like this code use the url "http://192.168.10.1/api/control?alert=101002" to send get request.Good luck!
I can't sending my array with DoPostMethod. Php code is working but I can't convert it to C#.Php code is
$numbers = array('50XXXXXXXX', '50XXXXXXXX', '50XXXXXXXX', '50XXXXXXXX');
$message = 'TEST';
$title = 'MAS API';
$veriler = array(
'apiNo' =>'1',
'user' =>’user_name’,
'pass' =>'pasword',
'mesaj'=>$message,
'numaralar' =>$numbers,
'baslik' =>$title,
);
$ozel_mesaj = sms_gonder("http://------",$veriler);
My code is below
DoRequest(string requestUrl, string requestMethod, string requestData){
WebRequest request = WebRequest.Create(requestUrl);
request.Method = requestMethod;
string postData = requestData;
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();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
this.ServerResponse = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();}
but i can send with ajax method
$.ajax({
"url": "myUrl",
"type": "post",
data:{
"apiNo": "apiNo",
"user": "user_name",
"pass": "password",
"mesaj": "DENEME123",
"numaralar":"numbers",
"baslik":"baslik"
},
success: function (data) {
if (data != NULL)
alert(data)
else
alert("Kayıt Eklenemedi")
}
I think my requestData is wrong. My RequestData is below:
string xmlRequest = "[{{apiNo=\"apiNo\"}, {user=\"user_name\"},{pass=\"password\"},{mesaj=\"DENEME2\"},{numaralar=\"{0000000000}\"},{baslik=\"baslik\"}}]";
How can I do that? Thanks
Here's a super basic way to do it. In this example, I am manually writing out the post parameters with a quick function that returns a string however, you could use JavascriptSerializer to properly convert a C# array (as well as reading inbound json returned by your webservice) which was recommended in another post answer.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
namespace doPostExampleForStackOverflow
{
static class Program
{
[STAThread]
static void Main()
{
string postReturn = doPostCall();
MessageBox.Show(postReturn);
Application.Exit();
}
static string doPostCall()
{
string URI = "https://webserver.com/post.php";
string myParameters = "username=" + Environment.UserName; /* Get local username (Windows) */
string result;
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
result = wc.UploadString(URI, myParameters);
}
if (result.Length <= 0) {
return "Nothing came back from the webserver.";
} else {
return result;
}
}
}
}
I solved my problem using this
string URL = "myURL";
WebClient webClient = new WebClient();
NameValueCollection formData = new NameValueCollection();
formData["apiNo"] = "apiNo";
formData["user"] = "user";
formData["pass"] = "pass";
formData["baslik"] = "baslik";
formData["numaralar"] = "{numaralar}";
formData["mesaj"] =" mesaj";
byte[] responseBytes = webClient.UploadValues(URL, "POST", formData);
string responsefromserver = Encoding.UTF8.GetString(responseBytes);
Console.WriteLine(responsefromserver);
webClient.Dispose();
and you can look at this link
As I have gone through the examples,I have come across only asynchronous http web request having callback methods,like:-
private void getList(string restApiPath, Dictionary<string, string> output, Type type, string label)
{
webRequest = (HttpWebRequest)WebRequest.Create(restApiPath);
path = restApiPath;
labelValue = label;
webRequest.Method = "POST";
webRequest.ContentType = Globals.POST_CONTENT_TYPE;
webRequest.Headers["st"] = MPFPConstants.serviceType;
webRequest.BeginGetRequestStream(result =>
{
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
// End the stream request operation
Stream postStream = request.EndGetRequestStream(result);
// Create the post data
string reqData = Utils.getStringFromList(output);
string encode = RESTApi.encodeForTokenRequest(reqData);
byte[] byteArray = Encoding.UTF8.GetBytes(encode);
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
request.BeginGetResponse(new AsyncCallback(GetResponseCallbackForSpecificConditions), request);
}, webRequest);
}
private void GetResponseCallbackForSpecificConditions(IAsyncResult ar)
{
//code
}
Kindly Suggest me if we can make a synchronous httpwebrequest for wp8?
Why not try this, it works in a Desktop app:
using (Stream TextRequestStream = UsedWebRequest.GetRequestStream())
{
TextRequestStream.Write(ByteArray, 0, ByteArray.Length);
TextRequestStream.Flush();
}
HttpWebResponse TokenWebResponse = (HttpWebResponse)UsedWebRequest.GetResponse();
Stream ResponseStream = TokenWebResponse.GetResponseStream();
StreamReader ResponseStreamReader = new StreamReader(ResponseStream);
string Response = ResponseStreamReader.ReadToEnd();
ResponseStreamReader.Close();
ResponseStream.Close();
Why not try restsharp?
sample POST code looks like,
RestClient _authClient = new RestClient("https://sample.com/account/login");
RestRequest _credentials = new RestRequest(Method.POST);
_credentials.AddCookie(_cookie[0].Name, _cookie[0].Value);
_credentials.AddParameter("userLogin", _username, ParameterType.GetOrPost);
_credentials.AddParameter("userPassword", _password, ParameterType.GetOrPost);
_credentials.AddParameter("submit", "", ParameterType.GetOrPost);
RestResponse _credentialResponse = (RestResponse)_authClient.Execute(_credentials);
Console.WriteLine("Authentication phase Uri : " + _credentialResponse.ResponseUri);
I am trying to upload an image programmatically via an API to another server. The API expects me to upload image in a byte array to be sent in a field: "image_content".
My implementation and calling code is as below. The web request hits the server but the server responds that the image is not present in my web request.
When I run the below code, I am getting error that the image is not present in the request. What am I missing here?
public static class FormUpload
{
private static readonly Encoding encoding = Encoding.UTF8;
public static HttpWebResponse MultipartFormDataPost(string postUrl, string userAgent, Dictionary<string, object> postParameters)
{
string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid());
string contentType = "multipart/form-data; boundary=" + formDataBoundary;
byte[] formData = GetMultipartFormData(postParameters, formDataBoundary);
return PostForm(postUrl, userAgent, contentType, formData);
}
private static HttpWebResponse PostForm(string postUrl, string userAgent, string contentType, byte[] formData)
{
HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;
if (request == null)
{
throw new NullReferenceException("request is not a http request");
}
// Set up the request properties.
request.Method = "POST";
request.ContentType = contentType;
request.UserAgent = userAgent;
request.ContentLength = formData.Length;
// Send the form data to the request.
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(formData, 0, formData.Length);
requestStream.Close();
}
return request.GetResponse() as HttpWebResponse;
}
private static byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary)
{
Stream formDataStream = new System.IO.MemoryStream();
bool needsCLRF = false;
foreach (var param in postParameters)
{
if (param.Value is FileParameter)
{
FileParameter fileToUpload = (FileParameter)param.Value;
// Add just the first part of this param, since we will write the file data directly to the Stream
string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n",
boundary,
param.Key,
fileToUpload.FileName ?? param.Key,
fileToUpload.ContentType ?? "application/octet-stream");
formDataStream.Write(encoding.GetBytes(header), 0, encoding.GetByteCount(header));
// Write the file data directly to the Stream, rather than serializing it to a string.
formDataStream.Write(fileToUpload.File, 0, fileToUpload.File.Length);
}
else
{
string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
boundary,
param.Key,
param.Value);
formDataStream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData));
}
}
// Add the end of the request. Start with a newline
string footer = "\r\n--" + boundary + "--\r\n";
formDataStream.Write(encoding.GetBytes(footer), 0, encoding.GetByteCount(footer));
// Dump the Stream into a byte[]
formDataStream.Position = 0;
byte[] formData = new byte[formDataStream.Length];
formDataStream.Read(formData, 0, formData.Length);
formDataStream.Close();
return formData;
}
public class FileParameter
{
public byte[] File { get; set; }
public string FileName { get; set; }
public string ContentType { get; set; }
public FileParameter(byte[] file) : this(file, null) { }
public FileParameter(byte[] file, string filename) : this(file, filename, null) { }
public FileParameter(byte[] file, string filename, string contenttype)
{
File = file;
FileName = filename;
ContentType = contenttype;
}
}
}
The code to call above function is:
// Read file data
FileStream fs = new FileStream("c:\\myimage.jpeg", FileMode.Open, FileAccess.Read);
byte[] data = new byte[fs.Length];
fs.Read(data, 0, data.Length);
fs.Close();
// Generate post objects
Dictionary<string, object> postParameters = new Dictionary<string, object>();
postParameters.Add("image_content",data);
// Create request and receive response
string postURL = "myurl";
string userAgent = "Mozilla";
HttpWebResponse webResponse = FormUpload.MultipartFormDataPost(postURL, userAgent, postParameters);
// Process response
StreamReader responseReader = new StreamReader(webResponse.GetResponseStream());
string fullResponse = responseReader.ReadToEnd();
webResponse.Close();
Response.Write(fullResponse);
In my opinion, you should use the MultipartFormDataContent class because it "Provides a container for content encoded using multipart/form-data MIME type.". Try this
public static HttpWebResponse MultipartFormDataPost(string postUrl, string userAgent, byte[] data)
{
string contentType;
byte[] formData = Program.GetMultipartFormData(data, out contentType);
return PostForm(postUrl, userAgent, contentType, formData);
}
public static byte[] GetMultipartFormData(byte[] data, out string contentType)
{
var byteArrayContent = new ByteArrayContent(data);
byteArrayContent.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
byteArrayContent.Headers.Add("image_content", "myimage.jpeg");
var content = new MultipartFormDataContent(String.Format("----------{0:N}", Guid.NewGuid())) { byteArrayContent };
contentType = content.Headers.ContentType.ToString();
return content.ReadAsByteArrayAsync().Result;
}
I was able to resolve the problem by the use of RestSharp Api mentioned in the stackoverflow question Upload file through c# using JSON request and RestSharp.
You all code is fine but you forgot To encode you parameter
try this
string postData = string.Format("--{0}\r\nContent-Disposition:
form-data; name=\"{1}\"\r\n\r\n{2}",
boundary,
HttpUtility.UrlEncode(param.Key),
HttpUtility.UrlEncode(param.Value));
In case of binary data
HttpUtility.UrlEncode(Convert.ToBase64String(byte[]))
try to use this code to add parameter in your request
NameValueCollection outgoingQueryString = HttpUtility.ParseQueryString(String.Empty);
outgoingQueryString.Add("uname", "username");
outgoingQueryString.Add("pname", "password");
string postdata = outgoingQueryString.ToString();
and write this postdata in you request
I have a webpage that need to pass data to web Service (SMS) and I tried to use WebRequest to do this work but when I use this class the following error appears:
Cannot close stream until all bytes are written
in the line after this line :
stOut.WriteLine(strNewValue,number,text);
What is the problem? I tried to use Flush() but didn't work either
public class SendSms
{
public SendSms(string number, string text)
{
string strNewValue;
string strResponse;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://www.buymessage.com/ostazSms/send.php");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
strNewValue = "usr=****&pwd=*****&to={0}&msg={1}";
req.ContentLength = strNewValue.Length;
using(StreamWriter stOut = new StreamWriter (req.GetRequestStream(), System.Text.Encoding.Unicode))
{
stOut.WriteLine(strNewValue,number,text);
}
StreamReader stIn = new StreamReader(req.GetResponse().GetResponseStream());
strResponse = stIn.ReadToEnd();
stIn.Close();
}
}
Your issue is that you call WriteLine, which probably doesn't send all the data.
Here is a snippet that encodes the post data and sends it all:
string strNewValue = string.Format("usr=****&pwd=*****&to={0}&msg={1}", "A", "B");
byte[] byteArray = Encoding.UTF8.GetBytes (strNewValue);
req.ContentLength = byteArray.Length;
using (Stream dataStream = req.GetRequestStream ()) {
dataStream.Write (byteArray, 0, byteArray.Length);
}