POST request, not sending anything, isset($_POST) always false - c#

I am new to C#. I tried all solutions to other questions and still i can't find what is wrong. My code is common in other answers but it seems to never send anything. I have tried in my own server and the company i'm working for server. I know this kind of answer has been answered many times before, but maybe i am missing something like others so this might be useful to someone besides me.
C# code:
var buttonSaveClicked = new MouseEventHandler((o, a) =>
{
var user_token = this.textApiKey.Text;
if (user_token.Length == 0) MessageBox.Show("API Key cannot be empty!", "API Key Error", MessageBoxButtons.OK, MessageBoxIcon.None);
var httpWebRequest = (HttpWebRequest) WebRequest.Create("http://localhost/networksWindows.php");
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"user_token\": \"batatas\", \"bata\": \"cook\"}";
System.Diagnostics.Debug.WriteLine(json);
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
System.Diagnostics.Debug.WriteLine(result);
User user = JsonConvert.DeserializeObject<User>(result);
if (user.status == "error") MessageBox.Show("Invalid API Key. Please make sure you have generated a API key and insert it correctly.", "API Key Error", MessageBoxButtons.OK, MessageBoxIcon.None);
else if (user.status == "success")
{
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadProc));
t.Start();
this.Close();
}
}
});
PHP script in my server:
<?php
$json = null;
if (isset($_POST['user_token']))
{
$json = $_POST['user_token'];
echo "user";
}
?>

If you want $_POST to understand your data, it has to be sent as form-encoded key=value&key2=value2, not as JSON.
If you want to post JSON, you need to decode it on server side:
$post = (array)json_decode(file_get_contents("php://input"));
if (isset($post['user_token'])) {
// ...
}
You can replace file_get_contents("php://input") with $HTTP_RAW_POST_DATA, but its availability depends on configuration.
P.S. streamWriter.Flush() call is redundant.

You have to decode your json post in PHP.
Try using this:
$json = json_decode($_POST);
if (isset($json['user_token']) {
$userToken = $json['user_token'];
}

Decode your json as an array:
$json = json_decode($_POST, true);

Related

Posting Json data to console

I'm trying to post Json data to my Console. I have the code that is requesting it. I think I either have my Parameters or something else that is wrong. I know I get to the site, but then I get a 500 Server Error. I'm stuck and any help would be appreciated. I took out the URL and USER and Pass. I left the other stuff. I have no idea what I'm doing as I usually work with SQL, but I was told to try this and see if I can get it to work. We are using a Console app with the .NET framework to try and get this to work. Please help as I'm out of ideas. Something might be wrong with the headers.Accept code as well.
I've tried changing the code where my params are, I've tried even google and looking at other stack over flow methods.
public static void Main(string[] args)
{
try
{
string webAddr ="MYURL";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Accept = "application/Json";
using (var streamWriter = new
StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
USER_ID = "MyUser",
PASSWORD = "MyPass",
Query_ID = "4444",
Parameters = ""Key" ("Original"),"Value" ("1.1323")
});
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
Console.WriteLine("Here is your Json Data.....");
Console.WriteLine(responseText);
Console.ReadLine();
//Response success above and error below
}
}
catch (WebException ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
}
}
For the Json data to show up in the Console.

Box API Create Shared link

I am trying to upload some documents to Box and create and retrieve a shared link for each of them.
This is the code I am using for it, but I always retrieve 403:access_denied_insufficient_permissions.
Any idea of why this is happening?
Hope you can help me! Thanks.
// CREATE THE FILE
BoxFileRequest req = new BoxFileRequest
{
Name = zipFile.Name,
Parent = new BoxRequestEntity { Id = newFolder.Id}
};
BoxFile uploadedFile = client.FilesManager.UploadAsync(req, stream).Result;
//REQUEST SHARED LINK
BoxSharedLinkRequest sharedLinkReq = new BoxSharedLinkRequest()
{
Access = BoxSharedLinkAccessType.open,
Permissions = new BoxPermissionsRequest
{
Download = BoxPermissionType.Open,
Preview = BoxPermissionType.Open,
}
};
BoxFile fileLink = fileManager.CreateSharedLinkAsync(uploadedFile.Id, sharedLinkReq).Result;
you need to give the access token and url. I have use the Following code and in JSON Format you will get the Response. For more reference check the box API document
HttpWebRequest httpWReq = HttpWebRequest)WebRequest.Create("https://api.box.com/2.0/folders/" + FolderID);
ASCIIEncoding encoding = new ASCIIEncoding();
string putData = "{\"shared_link\": {\"access\": \"open\"}}";
byte[] data = encoding.GetBytes(putData);
httpWReq.Method = "PUT";
httpWReq.Headers.Add("Authorization", "Bearer ");
httpWReq.ContentType = "application/json";
httpWReq.ContentLength = data.Length;
Use the httpwebrequest PUT method after this.
Mark it as Answer if its helpful.
It looks as if you are using the 3rd party BoxSync V2 API object. If you would like to just code to the API directly I had a similar issue that you are having. If you view this post you will see the answer. Here is the code I use and it works.
string uri = String.Format(UriFiles, fileId);
string response = string.Empty;
string body = "{\"shared_link\": {\"access\": \"open\"}}";
byte[] postArray = Encoding.ASCII.GetBytes(body);
try
{
using (var client = new WebClient())
{
client.Headers.Add("Authorization: Bearer " + token);
client.Headers.Add("Content-Type", "application/json");
response = client.UploadString(uri, "PUT", body);
}
}
catch (Exception ex)
{
return null;
}
return response;

send C# string to .PHP page

After looking a bit around I came to this page. Here, I found some code to send a C# string to a PHP page.
However, after implementing it in my own program it did not work. Here is my code:
private void executesend()
{
using (WebClient client = new WebClient())
{
client.UploadString(url,"POST",keys);
}
}
For the PHP part, I have:
<?php
mysql_connect("localhost", "", "") or die(mysql_error()); // Connect to database server(localhost) with username and password.
mysql_select_db("dimittv89_dayz") or die(mysql_error()); // Select registration database.
$name = $_GET["message"];
if ( $_SERVER['REQUEST_METHOD'] == 'POST' )
{
$name = file_get_contents('php://input');
$opdracht = "INSERT INTO 'keys', (`key`) VALUES ('$name')";
print $name;
}
if (mysql_query($opdracht)){
echo "succesfully registerd to the melloniax u wil now be returned to our main page";
}
else{
echo "hey something went wrong there ! please try again in a minute";
}
?>
In the same topic one of the users also said to try this:
php?fmessage=testtesttest"
and write down the output using
$name = $_GET["message"];
print $name;
This did not work either. Am I doing something wrong?
Thanks for the help already
Well sofar i found out its not the send value thats wrong but the get value :
Username = Registry.CurrentUser.OpenSubKey("Username", true);
Name = "" + Username.GetValue("Uid");
in the regedit menu it says that the value is a REG_BINARY, are these readable with getvalue ?
use this code for c# and php :
private void executesend()
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
string Data = "message="+keys;
byte[] postBytes = Encoding.ASCII.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)
{
MessageBox.Show("Please Check Your Internet Connection");
}
}
and php
<?php
mysql_connect("localhost", "", "") or die(mysql_error()); // Connect to database server(localhost) with username and password.
mysql_select_db("dimittv89_dayz") or die(mysql_error()); // Select registration database.
if (isset($_POST['message']))
{
$name = $_POST['message'];
$opdracht = "INSERT INTO keys (key) VALUES ('$name')";
print $name;
if (mysql_query($opdracht)){
echo "succesfully registerd to the melloniax u wil now be returned to our main page";
}
else{
echo "hey something went wrong there ! please try`enter code here` again in a minute";
}
}
?>

Posting score to Facebook app

I've been trawling the answers in SO concerning posting a score to a Facebook app, and I still can't get it to work. The code I'm using is here -
private const string FACEBOOK_POST_SCORE_URL = "https://graph.facebook.com/me/scores?access_token={0}";
public void PostScoreAsync(Action<FacebookResponse> response, FacebookScore score)
{
try
{
// Append the user's access token to the URL
Uri fullUri = new Uri(string.Format(FACEBOOK_POST_SCORE_URL, AccessToken));
string json = JsonConvert.SerializeObject(score);
var request = (HttpWebRequest)WebRequest.Create(fullUri);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(json);
}
request.BeginGetResponse(WebRequestCallback, new FacebookResult
{
Request = request,
Response = response
});
}
catch (ThreadAbortException)
{
throw;
}
catch (WebException ex)
{
if (response != null)
response(FacebookResponse.NetworkError);
}
catch (Exception ex)
{
if (response != null)
response(FacebookResponse.OtherError);
}
}
We're using webViews rather than iOS / Android Facebook SDKs, as we're building a cross-platform app in Mono.
Obviously I have the access token & the app appears to have full permissions to do what I want to do, which I allowed after login. Any thoughts appreciated!
I eventually found out (from a colleague) that the Facebook graph api won't take json encoded parameters, so we sorted it like so -
string parameters = "score=" + score.Score;
var request = (HttpWebRequest)WebRequest.Create(fullUri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(parameters);
}
Now it works fine - hopefully this'll help someone else not have the same problem.

Google Translate V2 cannot hanlde large text translations from C#

I've implemented C# code using the Google Translation V2 api with the GET Method.
It successfully translates small texts but when increasing the text length and it takes 1,800 characters long ( including URI parameters ) I'm getting the "URI too large" error.
Ok, I burned down all the paths and investigated the issue across multiple pages posted on Internet. All of them clearly says the GET method should be overriden to simulate a POST method ( which is meant to provide support to 5,000 character URIs ) but there is no way to find out a code example to of it.
Does anyone has any example or can provide some information?
[EDIT] Here is the code I'm using:
String apiUrl = "https://www.googleapis.com/language/translate/v2?key={0}&source={1}&target={2}&q={3}";
String url = String.Format(apiUrl, Constants.apiKey, sourceLanguage, targetLanguage, text);
Stream outputStream = null;
byte[] bytes = Encoding.ASCII.GetBytes(url);
// create the http web request
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.KeepAlive = true;
webRequest.Method = "POST";
// Overrride the GET method as documented on Google's docu.
webRequest.Headers.Add("X-HTTP-Method-Override: GET");
webRequest.ContentType = "application/x-www-form-urlencoded";
// send POST
try
{
webRequest.ContentLength = bytes.Length;
outputStream = webRequest.GetRequestStream();
outputStream.Write(bytes, 0, bytes.Length);
outputStream.Close();
}
catch (HttpException e)
{
/*...*/
}
try
{
// get the response
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
if (webResponse.StatusCode == HttpStatusCode.OK && webRequest != null)
{
// read response stream
using (StreamReader sr = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
{
string lista = sr.ReadToEnd();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(TranslationRootObject));
MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(lista));
TranslationRootObject tRootObject = (TranslationRootObject)serializer.ReadObject(stream);
string previousTranslation = string.Empty;
//deserialize
for (int i = 0; i < tRootObject.Data.Detections.Count; i++)
{
string translatedText = tRootObject.Data.Detections[i].TranslatedText.ToString();
if (i == 0)
{
text = translatedText;
}
else
{
if (!text.Contains(translatedText))
{
text = text + " " + translatedText;
}
}
}
return text;
}
}
}
catch (HttpException e)
{
/*...*/
}
return text;
}
Apparently using WebClient won't work as you cannot alter the headers as needed, per the documentation:
Note: You can also use POST to invoke the API if you want to send more data in a single request. The q parameter in the POST body must be less than 5K characters. To use POST, you must use the X-HTTP-Method-Override header to tell the Translate API to treat the request as a GET (use X-HTTP-Method-Override: GET).
You can use WebRequest, but you'll need to add the X-HTTP-Method-Override header:
var request = WebRequest.Create (uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers.Add("X-HTTP-Method-Override", "GET");
var body = new StringBuilder();
body.Append("key=SECRET");
body.AppendFormat("&source={0}", HttpUtility.UrlEncode(source));
body.AppendFormat("&target={0}", HttpUtility.UrlEncode(target));
//--
body.AppendFormat("&q={0}", HttpUtility.UrlEncode(text));
var bytes = Encoding.ASCII.GetBytes(body.ToString());
if (bytes.Length > 5120) throw new ArgumentOutOfRangeException("text");
request.ContentLength = bytes.Length;
using (var output = request.GetRequestStream())
{
output.Write(bytes, 0, bytes.Length);
}
The accepted answer appears to be out of date. You can now use the WebClient (.net 4.5) successfully to POST to the google translate API making sure to set the X-HTTP-Method-Override header.
Here is some code to show you how.
using (var webClient = new WebClient())
{
webClient.Headers.Add("X-HTTP-Method-Override", "GET");
var data = new NameValueCollection()
{
{ "key", GoogleTranslateApiKey },
{ "source", "en" },
{ "target", "fr"},
{ "q", "<p>Hello World</p>" }
};
try
{
var responseBytes = webClient.UploadValues(GoogleTranslateApiUrl, "POST", data);
var json = Encoding.UTF8.GetString(responseBytes);
var result = JsonConvert.DeserializeObject<dynamic>(json);
var translation = result.data.translations[0].translatedText;
}
catch (Exception ex)
{
loggingService.Error(ex.Message);
}
}
? What? it is trivial to post using C# - it is right there in the documentation.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
{
// Set type to POST
request.Method = "POST";
From there on you bascially put the data into fom fields into the content stream.
This is not "simulate a post meethod", it is fully doing a post request as per specifications.
Btw. hwhere does json enter here? You say "in C#". There is no need to use json?

Categories

Resources