Unity C#, WWWForm post to Python Flask Server - c#

Hi I am making a game in unity and I need to post information to my python flask server I think that the best method is to use the WWWForms in Unity C# but I can't seem to make it post. Here is my C# Unity Code:
IEnumerator Upload() {
WWWForm form = new WWWForm();
form.AddField("Username", "Stan");
form.AddField("Password", "123456");
using(UnityWebRequest www = UnityWebRequest.Post("http://myserver.com/newuser/", form)) {
yield return www.Send();
if(www.isError) {
Debug.Log(www.error);
}
else {
Debug.Log("Form upload complete!");
}
}
}
It alsways says "From upload complete" and I don't get any errors but when I check my SQL Database it hasn't received the information.
I am pretty sure that my server side code is right because I can post successfully to it through the Form but here is the code anyway:
Python Flask:
class Users(db.Model):
__tablename__ = "userstable"
userid = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(4096))
password = db.Column(db.String(4096))
#app.route("/", methods=["GET", "POST"])
def index():
return render_template("index.html")
#app.route("/newuser", methods=["GET", "POST"])
def NewUser():
if request.method == "GET":
return render_template("NewUser.html")
new_user = Users(username=request.form["Username"], password=request.form["Password"])
db.session.add(new_user)
db.session.commit()
return redirect(url_for('NewUser'))
Please Help, and if possible it would be nice to know how to do get requests as well, Thanks!
Stan.

Related

Get the link of the uploaded file with UnityWebRequest and php

I want to allow the user to use a local image from his machine and upload it to the server.
What I did is use UnityWebRequest in-game, load the image, send it to a PHP file on the server, and wait for the reply to remember the URL where the file si saved(to save it in Playfab later).
This is the code I made so far:
private readonly string setAvatarUrl = "http://myurl.com/setavatar.php";
private readonly string playerIdField = "playfabid";
private readonly string imageField = "img_avatar";
public IEnumerator SaveImageToDB(Texture2D image)
{
byte[] bytes = image.EncodeToPNG();
WWWForm form = new WWWForm();
form.AddField(playerIdField, player.playerId);
form.AddBinaryData(imageField, bytes, "avatar.png", "image/png");
UnityWebRequest www = new UnityWebRequest();
www = UnityWebRequest.Post(setAvatarUrl, form);
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.LogError(www.error);
}
else
{
string jsonFromDB = www.downloadHandler.text; // Return empty string
string imageUrl = JsonUtility.FromJson<string>(jsonFromDB);
Debug.Log($"JSON returned: {jsonFromDB}");
if (!string.IsNullOrEmpty(imageUrl))
{
// Save the url
}
Debug.Log("Image upload complete!");
}
}
And this is the PHP file:
<?php
ini_set('display_errors',1);
$idplayfab = $_POST['playfabid'];
$path = 'avatar/'.$idplayfab;
if(file_exists($path)) {
//dir exist
$files = glob($path.'/*');
foreach($files as $file){
if(is_file($file))
unlink($file);
}
} else {
//not exist
mkdir($path);
}
$uploadfile = $path ."/". basename($_FILES['img_avatar']['name']);
if (move_uploaded_file($_FILES['img_avatar']['tmp_name'], $uploadfile)) {
$array = array('result' => 'ok', 'url' => 'http://myurl.com/'.$uploadfile);
$json = json_encode($array);
return $json;
} else {
$array = array('result' => 'ko');
$json = json_encode($array);
return $json;
}
?>
The image is saved on the server but the problem is when I try to get the JSON to get the URL, the string is empty and I don't understand why.
I tried tons of solutions like this one or this one but I cannot figure it out.
I also tried to use the deprecated WWW instead, but still, it doesn't work.
I'm kinda new to PHP so maybe it could be the PHP part the problem I believe.
Not an PHP expert but:
Afaik return is only used to evaluate certain functions e.g. for success or in order to further handle the result of something before responding to the client on server side.
What you want to do is rather sending your content as the http result to the client
=> You should rather use echo or print which is used to generate the http output.

Unity: Post Request unable to connect to destination host

I'm familiar with Unity but new to trying to communicate with servers. I'm trying to set up a login screen but I'm having troubling Posting to the server properly. The strange part is the Get is working fine, but the Post turns up the following Error :
Cannot connect to destination host Network
UnityEngine.Debug:Log(Object)
LoginHandler:CheckForNetworkErrors(UnityWebRequest) (at
Assets/Scripts/LoginHandler.cs:120)
<LoginUser>c__Iterator2:MoveNext() (at Assets/Scripts/LoginHandler.cs:92)
.UnityEngine.SetupCoroutine:InvokeMoveNext(IEnumerator, IntPtr)
I'm using a test URL to make sure it was't an issue with the original. Both return the same error. The following code is sent once the player hits a login button. Any ideas on what im doing wrong here?
public IEnumerator LoginUser()
{
string testURL = "https://www.google.com/";
using (UnityWebRequest get = UnityWebRequest.Get(testURL))
{
yield return get.Send();
ParseCSRF(get.downloadHandler.text);
CheckForNetworkErrors(get);
}
WWWForm form = new WWWForm();
form.AddField("username", username.text);
form.AddField("password", password.text);
form.AddField("_csrf", csrf);
using (UnityWebRequest post = UnityWebRequest.Post(WWW.EscapeURL(testURL), form))
{
yield return post.SendWebRequest();
CheckForNetworkErrors(post);
}
}
public void CheckForNetworkErrors(UnityWebRequest www)
{
if(www.isNetworkError)
{
Debug.Log(www.error + " Network");
}
else if (www.isHttpError)
{
Debug.Log(www.error + " http");
}
else
{
Debug.Log("Form upload complete!" + www.downloadHandler.text);
}
}
I have tested with the code I wrote below:
void Start()
{
StartCoroutine(GetCrt());
}
IEnumerator GetCrt()
{
string testURL = "https://www.google.com/";
using (UnityWebRequest www = UnityWebRequest.Get(testURL))
{
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
Debug.Log("Get Request Completed!");
}
}
}
It's working fine.
For the post request you need a real form data, you can't send a post request to google.com.
Hope this help you.
Happy Coding!

How to build a safe API for Unity

I want to build an API for Unity. I noticed many APIs in Unity like Vuforia, requires developers to generate a key on website, and then paste the key into Unity editor, I wonder how does it work? When will Unity send the key to website to validate? Which protocol is this so I can research more on the internet?
When will Unity send the key to website to validate?
It depends. Some send the key during every request. Some send the key once, then generate a temporary token that will be used to make other requests.
Which protocol is this so I can research more on the internet?
Most web API use the REST protocol.
Usually POST or GET request methods.
I wonder how does it work?
It's not complicated. You need to know C#, MySQL and PHP(any back-end language). If you know these 3 languages, you can do it.
The MySQL is used to store user information such as username, password. User can go on the website and create a private key. That key will be saved on the database and linked to that user with MySQL.
When you make a request from Unity(C#) to the server, you can get the key from the user then embed in a form(WWWForm). You can use that form (WWWForm.AddField("API_KEY", "Your key")) to make request to the server with the WWW or UnityWebRequest API.
When the PHP receives request from your Unity. You read the form sent from Unity with PHP ($_POST["API_KEY"]) and then check if the key is in the database with MySQL. If the key exist, go ahead and do what the request want. If the key does not exist in the database echo error message.
That's it. Below is an example of an API that converts Image to Text. It requires key to function. Some functions are not implemented and is only used to show how API key authentication is done.
C#:
public Texture2D texture;
public void sendData()
{
string reqUrl = "http://yourServerUrl.com/app/imagetospeech.php";
WWWForm reqForm = new WWWForm();
//Add API key
reqForm.AddField("API_KEY", "AEH392HEIQSKLZ82V4HCBZL093MD");
//Add Image to convert to Text
reqForm.AddBinaryData("REQ_IMAGE", texture.EncodeToPNG());
WWW www = new WWW(reqUrl, reqForm);
StartCoroutine(WaitForRequest(www));
}
private IEnumerator WaitForRequest(WWW www)
{
yield return www;
//Check if we failed to send
if (string.IsNullOrEmpty(www.error))
{
UnityEngine.Debug.Log(www.text);
}
}
PHP:
<?php
function keyExist($keyInput)
{
//MySQL code to check if key is in the table
//$retval = NOT IMPLEMENTED!
if (!$retval) {
return false;
} else {
return true;
}
}
function convertImageToText($imageInput)
{
//$retval = NOT IMPLEMENTED!
if (!$retval) {
return "";
} else {
return $retval;
}
}
//Get API key from Unity
$apiKey = $_POST["API_KEY"];
//Check if API key exist
if (keyExist($apiKey)) {
//Get the image from Unity
$imageFile = $_FILES['REQ_IMAGE'];
if (!empty($imageFile)) {
//Success
echo convertImageToText($imageFile);
} else {
echo "Failed!";
}
}
?>

Sending data from unity to firebase producing error - Invalid data; couldn't parse JSON object

Just use Unity3d with Firebase I have a url of database where i want to send data.
Code below i am using
void Start()
{
BtnSendScore();
}
public void BtnSendScore() {
StartCoroutine(SendScore("Muhammad Faizan Khan", 100));
}
public IEnumerator SendScore(string name, int score){
string url = "https://xyz.firebaseio.com/scores.json";
WWWForm objForm =new WWWForm();
objForm.AddField("playerName", name);
objForm.AddField("score", score);
objForm.AddField("scoreDate", DateTime.Now.ToString());
WWW www = new WWW(url, objForm);
yield return www;
if (www.error == null)
{
Debug.Log("Adedd ::" + www.data);
}
else {
Debug.LogError("Error ::" + www.error);
}
}
Found this error? What the problem is i check on stackoverflow with jquery it talking about stringify.
Adedd ::{ "error" : "Invalid data; couldn't parse JSON object,
array, or value. Perhaps you're using invalid characters in your key
names." }
Remember I didn't mess with database in firebase just create database and got url. No keys added.
To write to the Firebase Database using the REST API, you'll need to pass the data as JSON in the body of the request. The Firebase REST API does not take the data as form parameters. See the Firebase documentation for some examples of how the API works.
This post looks like a promising starting point as does this answer.

How do I access a database in Unity?

I am trying to POST data to my database in Unity and it doesn't seem to be working. I know it is probably a very stupid mistake as I do have little knowledge in this field.
The C# script I have:
void logIn(string test) {
WWWForm form = new WWWForm();
form.AddField("action","send");
form.AddField("var1",test);
string url = "http://www.prizechief.com/unitycon.php";
WWW w = new WWW(url, form);
}
void Start() {
string sample = "Works";
logIn(sample);
}
My PHP code
<?php
$con = #mysqli_connect("server","un","pass", "db") or die("Could not connect " . mysqli_connect_error() . "Please try again later.");
$var1 = $_GET['var1'];
echo $var1;
mysqli_Query($con,"INSERT INTO test (var) VALUE ('$var1')");
?>
Also, a hint on how to use GET to receive information would be greatly appreciated!
Try this. That should do the WWW request and set $_GET['var1'] = to value1 in your PHP script. Now of course you will have to change that to your variable down the road. But just to test for now. If this doesn't work let me know what the debug logs print out.
void Start () {
string url = "http://www.prizechief.com/unitycon.php?var1=value1";
WWW www = new WWW(url);
StartCoroutine(WaitForRequest(www));
}
IEnumerator WaitForRequest(WWW www)
{
yield return www;
// check for errors
if (www.error == null)
{
Debug.Log("WWW Ok!: " + www.data);
} else {
Debug.Log("WWW Error: "+ www.error);
}
}
EDIT
Remember to go into Edit > Player Settings > Editor and change the URL to your domain.

Categories

Resources