Unity http WebRequest post/send data to a input-field - unity3d

I want to use UnityWebRequest to post data into an input field on a website for authorization.
I am able to post data to a website called "https://httpbin.org/post" and I got a success message beeing able to post data to a website:
Success {
"args": {},
"data": "",
"files": {},
"form": {
"data": "LOL"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "deflate, gzip",
"Content-Length": "8",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "UnityPlayer/2021.3.11f1 (UnityWebRequest/1.0, libcurl/7.84.0-DEV)",
"X-Amzn-Trace-Id": "Root=1-63753ab1-7eb673a229988fc954b32ae8",
"X-Unity-Version": "2021.3.11f1"
},
"json": null,
"origin": "31.18.250.181",
"url": "https://httpbin.org/post"
}
but this is just posting data into nothing and I want to post data into an input field like this:
<input type="text" name="_username">
It is for authorization with username and password and later I need to get the text data of a redirect site after logging in.
This is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using Exception = System.Exception;
public class TestWebRequest : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
try
{
string url = "www.ling.com";
WWWForm form = new WWWForm();
form.AddField("_username", "test");
var request = UnityWebRequest.Post(url, form);
//request.SetRequestHeader("Content-Type", "application/json");
//request.SetRequestHeader("Accept", "text/csv");
//request.SetRequestHeader("appKey", "ABC");
StartCoroutine(onResponse(request));
}
catch (Exception e) { Debug.Log("ERROR : " + e.Message); }
}
private IEnumerator onResponse(UnityWebRequest req)
{
yield return req.SendWebRequest();
if (req.isNetworkError)
Debug.Log("Network error has occured: " + req.GetResponseHeader(""));
else
Debug.Log("Success "+req.downloadHandler.text );
byte[] results = req.downloadHandler.data;
Debug.Log("Second Success");
// Some code after success
req.Dispose();
}
}
I can't show the exact link but as I said it has two input fileds one password and one username input field that need to be filled out for authorization and after that I need to submit the form to get redirected were I then want to get the text data from which works with get. I don't know if this is the best way of doing this but I need to access text data on the website that you have to be logged into and it can't be done with cookies (I think) because it are different credentials every time.
Thank you so much for helping!

When you're submitting data, you're actually filling out a form. And then you submit that form. What you need to understand first is that your app does not interact with a website's frontend, it only interacts with the form at hand.
So, say if the website is a PHP website, that would have some logic at some point that gets a user parameter and a password parameter as GET parameters, and would do something based on those.
I cannot recommend this tutorial series enough for what you're trying to do.
Secondly, please do not send passwords over Unity's Web Request utility as plaintext to any website. It is not secure at all. That is a very sensitive subject, you can start off by hashing every password you get as soon as you get it from Unity, and you may submit the hashed form to the database.
And for the last part, the best way of doing this is probably using an API rather than a simple PHP website like the tutorial above.

Related

Using Request Body in Azure Data Factory

I have a working GET request in Postman where the body contains the query as seen below
The body is as follows
{
"query": {
"bool": {
"must": [
{
"term": {
"Vrvirksomhed.cvrNummer": "12345678"
}
}
]
}
}
}
Now i'm trying to get the same GET to work in Aure Data Factory but somehow it seems that the syntax needs to be different as it' doesn't use it correctly. Does it need to be wrapped somehow ?
This is because the ADF will ignore the Request body when your Request method is GET. So it can't work.
You can click '{}' button to view the code of Copy activity.
Even if your request body has content, there isn't requestBody property in source.
If you change your request method to POST, it will show.
So you can change your request method to POST to have a try.

Post attachment in Service Now

I'm in a quandary on how to get this working.
In Postman, I can upload an attachment without any issue.
I'm uploading a simple text file.
The code from postmanshows this:
var form = new FormData();
form.append("uploadFile", "C:\\temp\\test.txt");
var settings = {
"async": true,
"crossDomain": true,
"url": "https://xxxxxxx.service-now.com/api/now/attachment/file?table_name=problem&table_sys_id=oiui5346jh356kj3h634j6hk&file_name=Toast",
"method": "POST",
"headers": {
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx==",
"Cache-Control": "no-cache",
"Postman-Token": "39043b7f-8b2c-1dbc-6a52-10abd25e91c1"
},
"processData": false,
"contentType": false,
"mimeType": "multipart/form-data",
"data": form
}
$.ajax(settings).done(function (response) {
console.log(response);
});
When I use this on an .asp page I get a 400 error and a response from the console that says:
"Failed to create the attachment. File part might be missing in the request."
How do you get the file you want attach into the code correctly. I thought hard coding it in would have worked. How do you get the code to find the file on the local users pc. Once I get this working I eventually want to have a file input button to select the file.
Thanks,
Scott
Your code looks fine except this line:
form.append("uploadFile", "C:\\temp\\test.txt");
Passing the file name as the second parameter won't work, according to the documentation of FormData.append here, you need to pass some blob/file object pointing to the document it self (not a string)
Now there are 2 possible scenarios:
Scenario 1
The user selects the file manually using a browse button
Here you need to add the input to your page and a trigger to upload the file when it's selected, something like below maybe:
uploadDataFile();
function uploadDataFile(fileInput) {
// creates the FormData object
var form = new FormData();
// get the first file in the file list of the input
// (you will need a loop instead if the user will select many files)
form.append("uploadFile", fileInput.files[0]);
// ... the rest of your AJAX code here ...
}
<input type="file" onchange="uploadDataFile(this)" />
Scenario 2
Uploading the file directly without user intervention
Here you need to construct the file object manually same as in this answer and then you will add it normally to your data object
function uploadDataFile() {
// creates the file object
var fileObject = new File (...);
// creates a data object and appends the file object to it
var form = new FormData();
form.append("uploadFile", fileObject);
// ... the rest of your AJAX code here ...
}
One final note
Please pay attention to the browser compatibility for FormData & File objects

Get an embeddable link from a public Facebook post's link

Question
Is it possible to get a permalink, which can be embedded successfully, to a facebook post from a link that follows the form https://www.facebook.com/{REFERENCED_PAGE_ID}/posts/{SOME_OTHER_ID} instead of the typical form https://www.facebook.com/{POSTER_ID}/posts/{POST_ID}? If so, how can it be done?
Background
Given a link such as the following (which cannot be embedded properly)
https://www.facebook.com/209447300380/posts/10153494075900381
I need to be able to programmatically produce the following link which can be embedded
https://www.facebook.com/photo.php?fbid=10151668558417282&set=a.244117472281.146601.8128837281&type=1
Normally the solution would be to query facebook with the statement
select permalink from stream where post_id='209447300380_10153494075900381'
However this query does not produce any data for me. My suspicion is that there is a problem with the original link: 209447300380 is not the ID of the posting page, but rather, the ID of the page being referenced. In cases where 209447300380 is the ID of the posting page, I can get a permalink from Facebook without any problems.
Miscellaneous Details
I am using an application access token with the read_stream permission. It may be the case that I do not have sufficient permissions; I'm not sure.
I'm also having issues getting a permalink for user posts (posts not posted by official 'pages'). I don't know if this is relevant.
It looks like a bug. Getting the permalink using FQL doesn't work whereas it works with Graph API. You should use Graph API then:
https://graph.facebook.com/209447300380_10153494075900381?fields=link&access_token=YOUR_TOKEN
Result:
{
"link": "https://www.facebook.com/photo.php?fbid=10151668558417282&set=a.244117472281.146601.8128837281&type=1",
"id": "209447300380_10153494075900381",
"created_time": "2013-11-08T18:08:46+0000"
}
Using the Graph API won't do too much changes in your app, I guess.
Unfortunately we've found the most reliable way to figure out the embeddable link is simply to try to access the starting link, and then follow where it redirects to. If the redirects end at facebook.com/login, then it isn't embeddable (to the public, anyway). Otherwise, the embeddable link should eventually be reached.
C# Sample:
public static string GetPermalink (string url) {
HttpWebRequest request;
HttpWebResponse response;
request = (HttpWebRequest) WebRequest.Create (url);
request.Method = "HEAD";
request.AllowAutoRedirect = true;
request.UserAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.16 (KHTML, like Gecko) Chrome/24.0.1304.0 Safari/537.16";
try { response = request.GetResponse () as HttpWebResponse; }
catch (WebException ex) { response = ex.Response as HttpWebResponse; }
using (response) {
string responseUri = null == response.ResponseUri ? null : response.ResponseUri.AbsoluteUri;
if (HttpStatusCode.OK == response.StatusCode) {
/* Ended at a login page. This post isn't viewable to the public. */
if (responseUri.StartsWith (#"https://www.facebook.com/login.php?") ||
responseUri.StartsWith (#"http://www.facebook.com/login.php?")) {
return null;
}
/* Found a public post. */
else return responseUri;
}
else return null;
}
}

Can't send a link to my own wall

I am developing a multi protocol client (currently Twitter, Facebook and Google Reader) for Windows using C# and wanted to extend its functions to send links to Facebook (currently I "only" have text status messages, comments and likes).
So I wrote this quite small method here:
public void PostLink(string text, string url)
{
if (string.IsNullOrEmpty(url))
{
PostTextStatus(text);
return;
}
dynamic parameters = new ExpandoObject();
parameters.message = text;
parameters.link = System.Web.HttpUtility.UrlEncode(url);
dynamic result = facebookClient.Post("me/links", parameters);
UpdateNewsFeed();
}
But I get the following error message back from Facebook: "(OAuthException) (#1500) The url you supplied is invalid"
But at least as I read the API docs this should be the right url and I tried it also with my user ID instead of "me" and without the UrlEncode - no luck so far.
Any help appreciated :)
(Using latest stable version für Facebook C# SDK)
The used client is initiated by
facebookClient = new FacebookClient(AccessToken);
dynamic result = (IDictionary<string, object>)facebookClient.Get("me");
if (result != null)
{
LoginSuccessfull = true;
}
}
and the AccesToken and its permissions were retrieved using
IDictionary<string, object> loginParameters = new Dictionary<string, object>
{
{ "response_type", "token" },
{ "appId", appId},
{ "secret", appSecret }
};
Uri redirectUri = new Uri("http://www.li-ghun.de/Nymphicus/");
loginUri = FacebookOAuthClient.GetLoginUrl(appId, null, _extendedPermissions, loginParameters);
with I think quite more than enough permissons:
private string[] _extendedPermissions = new[] {
"user_activities",
"user_birthday",
"user_checkins",
"user_education_history",
"user_events",
"user_games_activity",
"user_groups",
"user_hometown",
"user_interests",
"user_likes",
"user_location",
"user_notes",
"user_online_presence",
"user_photo_video_tags",
"user_photos",
"user_questions",
"user_relationship_details",
"user_relationships",
"user_religion_politics",
"user_status",
"user_subscriptions",
"user_videos",
"user_website",
"user_work_history",
"friends_about_me",
"friends_activities",
"friends_birthday",
"friends_checkins",
"friends_education_history",
"friends_events",
"friends_games_activity",
"friends_groups",
"friends_hometown",
"friends_interests",
"friends_likes",
"friends_location",
"friends_notes",
"friends_online_presence",
"friends_photo_video_tags",
"friends_photos",
"friends_questions",
"friends_relationship_details",
"friends_relationships",
"friends_religion_politics",
"friends_status",
"friends_subscriptions",
"friends_videos",
"friends_website",
"friends_work_history",
"create_event",
"create_note",
"email",
"export_stream",
"manage_friendlists",
"manage_notifications",
"manage_pages",
"offline_access",
"photo_upload",
"publish_actions",
"publish_checkins",
"publish_stream",
"read_friendlists",
"read_insights",
"read_mailbox",
"read_requests",
"read_stream",
"rsvp_event",
"share_item",
"status_update",
"video_upload",
};
Problem has been all the time at myself being stupid - I accidently exchanged the parameters when calling my method so the text of the entry was in the link property and vica versa.
Stupid me :(
I think your issue lies in the URL being posted as the link. Be sure that URL is visible to the linter (https://developers.facebook.com/tools/lint).
Another thing is to try playing with the Graph API Explorer tool and see if you can use it to post a link. If so, then try changing the application drop down to the app you're having issues with and try posting the link again.
In my case i was posting "http://localhost:3000" and facebook reject it. I tried with "www.google.com" and it works
The error I was getting was, even though the URL itself was valid, the og:image was being set to //example.com/example.jpg and missing http: or https:. I blame Facebook for this one, for not accepting a valid URL that any browser will accept, but the Debugger definitely helped identify this and solved the issue.
https://developers.facebook.com/tools/lint

Retrieve Facebook Post Comments Using Graph API

I tried to get Facebook comments using:
http://graph.facebook.com/[post_id]/comments
It results only 2 of 15 comments, and without count info.
{
"data": [
{
"id": "[post_id]",
"from": {
"name": "[name]",
"id": "[id]"
},
"message": "[message]",
"created_time": "2011-01-23T02:36:23+0000"
},
{
"id": "[id]",
"from": {
"name": "[name]",
"id": "[id]"
},
"message": "[message]",
"created_time": "2011-01-23T05:16:56+0000"
}
]
}
Anyone know why only 2 comments?
Also, I want to retrieve comments (default number) or retrieve comments with my limit number, and get its comments count. Any idea? (Please use Graph API).
You need to call it from a secure request https and provide an access_token:
https://graph.facebook.com/19292868552_118464504835613/comments?access_token=XXX
EDIT:
Added the object from the post document. try clicking the comments connection and then remove the access_token and try and see the difference.
In order to get the Like count and the comment count then you need to use a combination of the PostOwnerID and PostID not just the PostID
So for your example it would be:
https://graph.facebook.com/153125724720582_184234384932460/comments
Again, as mentioned in some of the other answers you need to use the https method along with an auth_token
I experienced the same problem with comments. The issue was that I was using an access token for a test user. Because test users don't have access to other FB users information, only the comments from pages were shown.
There is a word JUGAAR in Urdu that means, finding a way out, just to get the job done. So for like purpose I made this JUGAAR, I hope it helps.
$contents = file_get_contents("http://graph.facebook.com/" . $_GET['id'] . "/likes");
if (substr_count($contents, 'name')>0) {
echo substr_count($contents, 'name') . " people like this album";
}
By the way I am also new to this Fb stuff, I am looking for help to post comments. When I try to use graph.api./id/comments?access_token=sdfsfsdf&message="D" it still returns comments for the id instead of posting.
As a sanity check, do you have "read_stream" permission? I can see the full comments with my access token that uses "read_stream". As mentioned by other people, you have to use https and access token as well...
Try to authenticate via App Login (http://developers.facebook.com/docs/authentication) and then to call GraphAPI with access_token prarameter.
You can do something like this to avoid the whole count of comments issues:
Get the object's (a post is considered an object in the Graph API) ID-as I understand from your question, you already have it?
Create a Comments Social Plugin with this ID, and get the code for it.
Embed the code in your site.
This will result in all the comments for this object.
To get the count of comments per object, you can execute an fql query, something like this:
SELECT comments FROM stream WHERE post_id = [yourpostid]
This will return in the comments array under the count parameter the number of counts for this object.
SELECT comments FROM stream WHERE post_id = [yourpostid] shall not work in this case ..
the id which is returned after making a graph call successfully to post on a user's wall (using access_token of an application ) is of the form abcdef_qwerty ( underscore seperated id )
where as the post id which is mapped in the post_id of the comments table is of the form "lmnop" ..
to get the counts of like and comments on this post id of form "abcdef_qwerty" making a graph call withh app generated access token seems to be the only solution ..
something like:
https://graph.facebook.com/100002619172565_117323155031656?access_token=xxxxxxxxxxxxx
After Successfully Login call this method facebookComments()
parameters.putString("fields", "message"); .............// Its Important
AccessToken accessToken = AccessToken.getCurrentAccessToken();
public void facebookComments() {
try {
getFriends(accessToken, new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
Log.e("keshav", "one" + response);
CommonMethod.showAlert("res --> " + response, MainActivity.this);
}
}
);
} catch (Exception e) {
CommonMethod.showAlert("Exception is -> " + e, MainActivity.this);
}
}
public void getFriends(AccessToken token, GraphRequest.Callback callback)
{
// TODO Comments Working but id return only
GraphRequest requestt = new GraphRequest(token, "744511125731315_751199848395776/comments",
null, HttpMethod.GET, callback);
Bundle parameters = new Bundle();
parameters.putString("fields", "id"); // todo in use imp
parameters.putString("fields", "name"); // todo in use imp
parameters.putString("fields", "from"); // todo in use imp
parameters.putString("fields", "message"); // todo in use imp
requestt.setParameters(parameters);
requestt.executeAsync();
}
It results only 2 of 15 comments
Add a limit parameter to the URL:
http://graph.facebook.com/[post_id]/comments?limit=1000&access_token=XXX
This should show all the comments.