I want to send json request from c# to php file and save data into text file but php file can not read data
this is my code
User user = new User { id = 1, name = "Bob", address = "password", phone = "0111111111", activation = true };
string json = "{\"id\":" + "\"" + user.id + "\""
+ ",\"name\":" + "\"" + user.name + "\""
+ ",\"address\":" + "\"" + user.address + "\""
+ ",\"activation\":" + "\"" + user.activation + "\"}";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:8080/test.php");
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = json.Length;
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Close();
var httpResponse = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
and php file id
<?php
$data = json_decode(file_get_contents('php://input'), true);
$file = "LogFile.txt";
$handle = fopen($file, 'a') or die('ERROR: Cannot write to file: ' . $file);
date_default_timezone_set('Europe/Amsterdam');
fwrite($handle, $data);
fclose($handle);
echo "SUCCESS";
?>
please what must i do in php file to read right? thank you
This minimal piece of code was all I needed to solve my own problem:
$_data = json_decode(file_get_contents('php://input'), true);
if (isset($_data)) {
$file = "users.txt";
file_put_contents($file, json_encode($_data));
}
Related
Out of no where, my twitter API calls, specificly my first step in the 3-legged auth, stopped working. I've compared the timestamps, keys and everything with the OAuth signature generator tool, and they all match (execpt oauth_nonce but thats the point I guess). Here is my code. Any suggestions or small observations would be appreciated.
protected void RequestToken()
{
string oauthcallback = Request.Url.Host + "/TwitterCallback.aspx";
string oauthconsumerkey = "xxx-consumerkey";
string oauthconsumersecret = "xxx-consumerSecret";
string oauthtokensecret = string.Empty;
string oauthtoken = string.Empty;
string oauthsignaturemethod = "HMAC-SHA1";
string oauthversion = "1.0";
string oauthnonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
TimeSpan timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
string oauthtimestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
string url = "https://api.twitter.com/oauth/request_token?oauth_callback=" + oauthcallback;
SortedDictionary<string, string> basestringParameters = new SortedDictionary<string, string>();
basestringParameters.Add("oauth_version", oauthversion);
basestringParameters.Add("oauth_consumer_key", oauthconsumerkey);
basestringParameters.Add("oauth_nonce", oauthnonce);
basestringParameters.Add("oauth_signature_method", oauthsignaturemethod);
basestringParameters.Add("oauth_timestamp", oauthtimestamp);
basestringParameters.Add("oauth_callback", Uri.EscapeDataString(oauthcallback));
//Build the signature string
string baseString = String.Empty;
baseString += "POST" + "&";
baseString += Uri.EscapeDataString(url.Split('?')[0]) + "&";
foreach (KeyValuePair<string, string> entry in basestringParameters)
{
baseString += Uri.EscapeDataString(entry.Key + "=" + entry.Value + "&");
}
//Remove the trailing ambersand char last 3 chars - %26
//baseString = baseString.Substring(0, baseString.Length - 3);
//Build the signing key
string signingKey = Uri.EscapeDataString(oauthconsumersecret) +
"&" + Uri.EscapeDataString(oauthtokensecret);
//Sign the request
HMACSHA1 hasher = new HMACSHA1(new ASCIIEncoding().GetBytes(signingKey));
string oauthsignature = Convert.ToBase64String(
hasher.ComputeHash(new ASCIIEncoding().GetBytes(baseString)));
//Tell Twitter we don't do the 100 continue thing
ServicePointManager.Expect100Continue = false;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(#url);
string authorizationHeaderParams = String.Empty;
authorizationHeaderParams += "OAuth ";
authorizationHeaderParams += "oauth_nonce=" + "\"" +
Uri.EscapeDataString(oauthnonce) + "\",";
authorizationHeaderParams += "oauth_signature_method=" + "\"" +
Uri.EscapeDataString(oauthsignaturemethod) + "\",";
authorizationHeaderParams += "oauth_timestamp=" + "\"" +
Uri.EscapeDataString(oauthtimestamp) + "\",";
authorizationHeaderParams += "oauth_consumer_key=" + "\"" +
Uri.EscapeDataString(oauthconsumerkey) + "\",";
authorizationHeaderParams += "oauth_signature=" + "\"" +
Uri.EscapeDataString(oauthsignature) + "\",";
authorizationHeaderParams += "oauth_version=" + "\"" +
Uri.EscapeDataString(oauthversion) + "\"";
webRequest.Headers.Add("Authorization", authorizationHeaderParams);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
//Allow us a reasonable timeout in case Twitter's busy
webRequest.Timeout = 3 * 60 * 1000;
try
{
HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse;
Stream dataStream = webResponse.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
var uri = new Uri("https://test.dk?" + responseFromServer);
var token = HttpUtility.ParseQueryString(uri.Query).Get("oauth_token"); ;
var tokensecret = HttpUtility.ParseQueryString(uri.Query).Get("oauth_token_secret");
Response.Write(responseFromServer);
Response.Redirect("https://api.twitter.com/oauth/authorize?force_login=true&oauth_token=" + token);
}
catch (Exception ex)
{
Response.Write(ex.GetBaseException());
}
}
The error obviously happens when I do the HTTP request webRequest.GetResponse()
It returns a 401 unauthorized
Apperently you have to include the oauth version number in the URL now, or else it will fall back to the oldest version (or maybe the newest, can't remember).
Providing /oath/1.0/ or /1.0/oauth/ or what ever solved my issue as i recall it (it's been a while).
I would like to try upload a mp3 file to my soundcloud account. I have written this code for this job.
WebClient client = new WebClient();
string postData = "client_id=" + "xxxxx"
+ "&client_secret=" + "xxx"
+ "&grant_type=password&username=" + "xxx" //your username
+ "&password=" + "xxx";//your password :)
string soundCloudTokenRes = "https://api.soundcloud.com/oauth2/token";
string tokenInfo = client.UploadString(soundCloudTokenRes, postData);
tokenInfo = tokenInfo.Remove(0, tokenInfo.IndexOf("token\":\"") + 8);
string token = tokenInfo.Remove(tokenInfo.IndexOf("\""));
System.Net.ServicePointManager.Expect100Continue = false;
var request = WebRequest.Create("https://api.soundcloud.com/tracks") as HttpWebRequest;
request.CookieContainer = new CookieContainer();
//some default headers
request.Accept = "*/*";
request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
request.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
request.Headers.Add("Accept-Language", "en-US,en;q=0.8,ru;q=0.6");
//file array
var files = new UploadFile[] { new UploadFile(filePath, "#/" + filePath, "application/octet-stream") };
//other form data
var form = new NameValueCollection();
form.Add("track[title]", "biksad");
form.Add("track[sharing]", "public");
form.Add("oauth_token", token);
form.Add("format", "json");
form.Add("Filename", fileName);
form.Add("Upload", "Submit Query");
string lblInfo;
try
{
using (var response = HttpUploadHelper.Upload(request, files, form))
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
lblInfo = reader.ReadToEnd();
}
}
}
catch (Exception ex)
{
lblInfo = ex.ToString();
}
}
When I debug this code part. I get (422) Unprocessable Entity error in catch block. Why I get this error? How can solve this problem?
Check the Soundcloud documentation:
http://developers.soundcloud.com/docs#errors
422 - "The request looks alright, but one or more of the parameters looks a little screwy. It's possible that you sent data in the wrong format (e.g. an array where we expected a string)."
Im trying to convert Java program to C#. This programe sent JSON object to server using a HTTP POST. Java program works fine. return 200. But C# program return 400 (bad request). What can be the cause
Java Code
String base_url = "https://test-url.com";
String username = "test-user";
String password = "test-pass";
String client_id = "test-client";
String client_secret = "test-key";
String loginUrl = base_url + "session/login";
Charset utf8 = Charset.forName("UTF-8");
ContentType jason_content_type = ContentType.create("application/json", utf8);
try {
HttpClient c = HttpClients.custom().setUserAgent(client_id + "/1.0").build();
HttpPost p = new HttpPost(loginUrl);
String json_str = "{" + "\"userId\":\"" + username + "\"," + "\"password\":\"" + password + "\"," + "\"clientId\":\"" + client_id + "\"," + "\"clientSecret\":\"" + client_secret + "\"" + "}";
p.setEntity(new StringEntity(json_str, jason_content_type));
HttpResponse r = c.execute(p);
int status = r.getStatusLine().getStatusCode();
} catch (IOException e) {
System.out.println(e);
}
C# Code
string base_url = "https://test-url.com";
string username = "test-user";
string password = "test-pass";
string client_id = "test-client";
string client_secret = "test-key";
string login_url = base_url + "session/login";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(login_url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = WebRequestMethods.Http.Post;
httpWebRequest.UserAgent = client_id + "/1.0";
httpWebRequest.ProtocolVersion=HttpVersion.Version11;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream(), Encoding.UTF8))
{
string json_str = "{" + "\"userId\":\"" + username + "\"," + "\"password\":\"" + password + "\"," + "\"clientId\":\"" + client_id + "\"," + "\"clientSecret\":\"" + client_secret + "\"" + "}";
streamWriter.Write(json_str);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
Try out adding in C# :
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
While posting data I am getting issue. The issue is in the & character. I am posting a string which may contain anything. like "this&this, how are you?".
But in the above case only "this" is sending. String from the character & is stripped.
Code I tried:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://mywebsite.com/import.php");
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write("tname=sanam&temail=sanam#" + Guid.NewGuid().ToString("N") + ".com&tbody=" + this.body + "&ttitle=" + this.title);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
retStr = streamReader.ReadToEnd();
}
//retStr = "POST: " + this.body;
}
Does anybody know how to send anything to the server using C#?
Thanks in advance.
Encode the free text fields trough
System.Web.HttpUtility.UrlEncode()
IE:
streamWriter.Write("tname=sanam&temail=sanam#" + Guid.NewGuid().ToString("N") + ".com&tbody=" + HttpUtility.UrlEncode(this.body) + "&ttitle=" + HttpUtility.UrlEncode(this.title));
I get this error "The remote server returned an error: (530) Not logged in." while uploading the file using FtpWebRequest.
Error occurs only when I transfer the files to path having subfolders, otherwise it perfectly works fine.
Uploading large files about 5 to 10 MB, it gets timed out.
void FtpTransfer(string siteName, string portNumber, string ftpUser, string ftpPassword, string destPath)
{
FtpWebRequest request;
DateTime now = DateTime.Now;
string now_string =
(now.Year).ToString()
+ "_" +
(now.Month).ToString("0#")
+ "_" +
(now.Day).ToString("0#");
foreach (object item in listBox1.Items)
{
string srcFile = item.ToString();
lblSource.Text = srcFile;
Uri uri = new Uri(srcFile);
string destFile = srcFile.Replace(lblPath.Text, "").Replace("\\\\", "\\").Replace("\\", "/").Replace("www/","");
Configuration oConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
int timeout = int.Parse(oConfig.AppSettings.Settings["TimeOut"].Value);
if (siteName == "mysite1.co.in" || siteName == "sd1.mysite2.net")
destFile = "ftp://" + siteName + ":" + portNumber + "/" + siteName + "/_test" + destFile; //error here
else
destFile = "ftp://" + siteName + ":" + portNumber + "/" + siteName + destFile; //no error
lblDestn.Text = destFile;
request = (FtpWebRequest)WebRequest.Create(destFile);
request.Credentials = new NetworkCredential(ftpUser, ftpPassword);
request.Timeout = 6000;
request.Method = WebRequestMethods.Ftp.UploadFile;
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = true;
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader(#srcFile);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
string path = System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);
System.IO.StreamWriter w = System.IO.File.AppendText(path + "\\log_" + now_string + ".txt");
w.WriteLine(DateTime.Now.ToString("yyy-MM-dd HH:mm:ss")
+ " "
+ srcFile
+ " "
+ destFile
+ " "
+ response.StatusDescription);
w.Close();
response.Close();
}
I am assuming that you have already attempted to do the same operation through a standard FTP client. If not, try that. I would then use Wireshark to make sure that is the response coming from the server and verify that the credentails are being sent. After that is verified, check with the FTP owner and make sure the server is configured appropriately.
I do not exactly know the solution for your problem. but some suggestions:
Use using(...) on IDisposable classes when ever possible. This promotes proper resource releasing and cleanup when you are finished with it. MSDN: Using
You use a timeout of 6000 miliseconds, may you should increase it for huge files or use your local variable timeout (read from you app settings).
Improved code with using:
private void FtpTransfer(string siteName, string portNumber, string ftpUser, string ftpPassword, string destPath)
{
DateTime now = DateTime.Now;
string now_string =
(now.Year).ToString()
+ "_" +
(now.Month).ToString("0#")
+ "_" +
(now.Day).ToString("0#");
foreach (object item in listBox1.Items)
{
string srcFile = item.ToString();
lblSource.Text = srcFile;
Uri uri = new Uri(srcFile);
string destFile = srcFile.Replace(lblPath.Text, "").Replace("\\\\", "\\").Replace("\\", "/").Replace("www/", "");
Configuration oConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
int timeout = int.Parse(oConfig.AppSettings.Settings["TimeOut"].Value);
if (siteName == "mysite1.co.in" || siteName == "sd1.mysite2.net")
destFile = "ftp://" + siteName + ":" + portNumber + "/" + siteName + "/_test" + destFile; //error here
else
destFile = "ftp://" + siteName + ":" + portNumber + "/" + siteName + destFile; //no error
lblDestn.Text = destFile;
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(destFile);
request.Credentials = new NetworkCredential(ftpUser, ftpPassword);
request.Timeout = 6000;
request.Method = WebRequestMethods.Ftp.UploadFile;
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = true;
// Copy the contents of the file to the request stream.
byte[] fileContents;
using (StreamReader sourceStream = new StreamReader(#srcFile))
{
fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
}
request.ContentLength = fileContents.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(fileContents, 0, fileContents.Length);
}
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
string path = System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);
System.IO.StreamWriter w = System.IO.File.AppendText(path + "\\log_" + now_string + ".txt");
w.WriteLine(DateTime.Now.ToString("yyy-MM-dd HH:mm:ss")
+ " "
+ srcFile
+ " "
+ destFile
+ " "
+ response.StatusDescription);
}
}
}