Add flag to UnityWebRequest - rest

I am trying to make a POST request to webpage that expects the --data field to be filled with some data to be processed. I'm pretty much trying to recreate this curl request, but with UnityWebRequest.
curl -X POST http://localhost:8000/clic/say?text=Make+the+gene+set --data '{"geneSetMembers":["UST"],"geneSetName":"selection0"}'
The UnityWebRequest documentation mentions that GET requests don't set any flags other than the url, but it's not clear if no other custom options exist for posts. Is there some way to format a WWWform or something that will hold the data such that the server will recognize it?
var form = new WWWForm();
// some way to plug in the jsonified data to the form
webRequest = UnityWebRequest.Post(url + route + to_say, form);
webRequest.downloadHandler = new DownloadHandlerBuffer();
webRequest.SetRequestHeader("Content-Type", "application/json");
webRequest.SendWebRequest();
// etc etc
I've tried just giving the form a field named "data" a la
form.AddField("data", "{ \"geneSetMembers\":[\"UST\"],\"geneSetName\":\"selection0\"}");
but the server does not like it, saying it "got error Invalid JSON literal name: data" So clearly that's the wrong syntax for it
EDIT: put lines in the same order they were in original code. Sorry, I have commented lines between them

Maybe your server doesn't like to receive the data as a field called data.
This ofcourse depends totally on the PHP code we don't see since you didn't share that part. b
But at least I can tell you that --data or also simply -d in curl refer to the entire data section and is not a field called data.
You could try to instead use a MultiPartFormDataSection passing just the data itself without a specific field name
var data = "{\"geneSetMembers\":[\"UST\"],\"geneSetName\":\"selection0\"}";
var form = new List<IMultiFormPart>{ new MultiPartFormDataSection(data) };
webRequest = UnityWebRequest.Post(url + route + to_say, form);
yield return webRequest.SendWebRequest();
which is now sent as content-type multipart/form-data though ...
Another alternative if your server really needs to receive a content-type application/json might be to "manually" compose the request e.g. like
var data = "{\"geneSetMembers\":[\"UST\"],\"geneSetName\":\"selection0\"}";
var request = new UnityWebRequest(url + route + to_say, "POST");
var bodyRaw = Encoding.UTF8.GetBytes(data);
request.uploadHandler = (UploadHandler) new UploadHandlerRaw(bodyRaw);
request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
yield return request.SendWebRequest();
Though of you look close now this seems actually not to be the case since if you read the man curl
(HTTP) Sends the specified data in a POST request to the HTTP server, in the same way that a browser does when a user has filled in an HTML form and presses the submit button. This will cause curl to pass the data to the server using the content-type application/x-www-form-urlencoded
which is actually exactly the default content type used by the simple string version of UnityWebRequest.Post.
So thinking about it it should actually be as simple as using the pure string version of UnityWebRequest.Post:
var data = "{\"geneSetMembers\":[\"UST\"],\"geneSetName\":\"selection0\"}";
var request = UnityWebRequest.Post(url + route + to_say, data);
yield return request.SendWebRequest();

Related

I POST my image by python through WP REST API, but the response is just the array of items in media library

First of all, I have found out what's wrong with my python code, but I really want some one to tell me how it popped out because I'm just a noob amateur.
I tried to post my album collected on my wordpress by using my python script as usual, but I got an unexpected throw-out when it start to image upload. My img upload function just like this:
def restImgUL(imgPath,imgName,token):
url='http://www.rainloongmusic.com/wp-json/wp/v2/media/'
file_extension = os.path.splitext(imgPath)[-1]
img = open(imgPath,'rb')
imgName = imgName.replace(";","")
_json = {
"title":imgName,
'caption': imgName,
"alt_text":imgName,
"description":imgName,
"status":"publish"
}
image_name = f"{imgName}{file_extension}"
headers = { 'Content-Type': '','Content-Disposition' : 'attachment; filename=%s'%image_name.encode("utf-8").decode("latin1"),"Authorization":"Bearer %s"%token}
res = requests.post(url=url,data=img,headers=headers,json=_json)
rrr = res.json()
if "id" in rrr:
return rrr["id"]
else:
print(rrr)
sys.exit()
The wrong response is an array include items in my first page of media library. I found some clues in rest api handbooks. If I attempt to GET /wp/v2/media, response will be like what I've recieved. But I use POST type request in my python code, I don't really understand what happened there. I have no choice but to try some other methods to bypass this problem. I tried to make a new endpoint and write something like this:
add_action( 'rest_api_init', function () {
register_rest_route( 'rlra/v1', '/media', array(
'methods' => 'POST',
'callback' => 'cmupload',
) );
} );
function cmupload(){
return "This is a test!!!"
}
However, I got rest_no_route when I POST to it. I changed the methods to GET eventually, and got the right text from my server. I think maybe something changed my POST request into a GET one? I tried to figure out with Charles, and found my connection with 302 permanent redirect. So I check my request link and change http into https, everything works.
So, could anyone tell me why a 302 redirect will change my POST request into GET, I've been worn-out due to the lost letter "s" in these days.

How to connect to Webservice REST with POST from Power BI

I am trying to connect to a webservice through Power BI but I still do not achieve result, first try to use the Web data source and with the Advanced Use add the Header that in my case is Content-Type and its value is application/json and additional as Body I have a token
Where I get as a result the following:
Additional also try to use as source "Blank Query", where I accessed the advanced editor section and add the following Query:
I get as an error the following:
To make sure that the Webservice works correctly and obtains a result I have used the Advanced REST Client tool and I have made the following configuration:
Where you can see that the Headers section I have added the Header name Content-Type and the value of the Header Value is application/json, in the Body section is where I have added the token
With this I realize that my Webservice gets an answer and that the service is working correctly, I would like someone to give me a little guidance in a short time to perform correctly
Supply the content to switch the method from GET to POST eg
Perform a POST against a URL, passing a binary JSON payload and
parsing the response as JSON.
https://learn.microsoft.com/en-us/powerquery-m/web-contents#example-2
let
url = "https://postman-echo.com/post",
headers = [#"Content-Type" = "application/json"],
postData = Json.FromValue([token = "abcdef"]),
response = Web.Contents(
url,
[
Headers = headers,
Content = postData
]
),
jsonResponse = Json.Document(response),
json = jsonResponse[json]
in
json
or
let
url = "https://postman-echo.com/post",
headers = [#"Content-Type" = "application/json"],
postData = Text.ToBinary("{ ""token"":""abcdef""}"),
response = Web.Contents(
url,
[
Headers = headers,
Content = postData
]
),
jsonResponse = Json.Document(response),
json = jsonResponse[json]
in
json

Algolia - Unity/C# | How to use REST API in Unity

I'm trying to use the PLACES REST API of Algolia in Unity. https://community.algolia.com/places/api-clients.html#rest-api
The documentation provides examples of how to use it:
$ curl -X POST ‘https://places-dsn.algolia.net/1/places/query’
-H ‘X-Algolia-Application-Id: YourApplicationId’
-H ‘X-Algolia-API-Key: YourAPIKey’
–data ‘{“query”: “Paris”}’
Using UnityWebRequest, the syntax is the following:
UnityWebRequest www = UnityWebRequest.Post("https://places-dsn.algolia.net/1/places/query", form);
www.SetRequestHeader("X-Algolia-Application-Id", "XXXXX");
www.SetRequestHeader("X-Algolia-API-Key", "XXXXXX");
Where form has been:
Unity WWWForm
WWWForm form = new WWWForm();
form.AddField("data", "{\"query\": \"Paris\"}");
AND
WWWForm form = new WWWForm();
form.AddField("query", "Paris");
string
"{\"query\": \"Paris\"}"
string json
JsonUtility.ToJson(new AlgoliaQuery { query = "paris" });
The connection is successful but I keep receiving errors in return
{"message":"lexical error: invalid char in json text. Around '%7b%22quer' near line:1 column:1","status":400}
The error varies in the invalid char position depending on the type of attempt.
Please, if you can provide any help would be amazing!
Thanks!
I got the answer! https://forum.unity.com/threads/unitywebrequest-post-url-jsondata-sending-broken-json.414708/
var request = new UnityWebRequest("https://places-dsn.algolia.net/1/places/query", "POST");
byte[] bodyRaw = Encoding.UTF8.GetBytes(query);
request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
request.SetRequestHeader("X-Algolia-Application-Id", "XXXXXX");
request.SetRequestHeader("X-Algolia-API-Key", "XXXXXXX");
yield return request.SendWebRequest();
it works now. I hope this will be useful for someone.
If the Unity project can leverage .NET Standard or .NET 4.5 you could directly use the Algolia .NET API client to embed Algolia search in your project.
Here is a sample application I made using both Algolia and Unity.

REST Hammock not adding content to post body

I've been fiddling a POST request that isn't working. What I've found is that the content of the request is empty even though I believe I'm adding it correctly (even though there aren't any docs available that I can find).
var json = JsonConvert.SerializeObject(payload);
var client = new RestClient
{
Authority = "",
Credentials = OAuthCredentials.ForProtectedResource(Registration.ClientKey,
Registration.ClientSecret,
AuthorizationToken.Token,
AuthorizationToken.Secret),
Method = WebMethod.Post,
Path = url
};
var request = new RestRequest();
request.AddHeader("Accept", ContentType);
request.AddHeader("Content-Type", ContentType);
request.AddPostContent(Encoding.UTF8.GetBytes(json));
response = client.Request(request);
I'm not having any trouble with authorization. I just kept getting a 400 error. After capturing the request with Fiddler, I noticed that content-length was 0. What am I missing? Do I need to do something in addition to AddPostContent? When I check the request object right before executing, there is content in PostContent, but it's as if Hammock isn't adding it to the request. I am using the latest full nuget (not ClientProfile).

Azure encoding job via REST Fails

I am trying to upload a video and encode it via azure rest service.
I have now hit the step of encoding the video but I am having difficulties with the request.
The following code shows my request:
var joburl = res.RequestMessage.RequestUri + "Jobs";
client = new HttpClient();
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Bearer " + token);
client.DefaultRequestHeaders.Add("x-ms-version", "2.8");
client.DefaultRequestHeaders.Add("DataServiceVersion", "3.0");
client.DefaultRequestHeaders.Add("MaxDataServiceVersion", "3.0");
client.DefaultRequestHeaders.Add("x-ms-date", date);
//accept
t = new NameValueHeaderValue("odata", "verbose");
type = new MediaTypeWithQualityHeaderValue("application/json");
type.Parameters.Add(t);
client.DefaultRequestHeaders.Accept.Add(type);
result = await client.PostAsync(joburl,json);
the url:https://wamsamsclus001rest-hs.cloudapp.net/api/Jobs
the json:
{"Name":"khgfiuydencodingjob","InputMediaAssets":[{"__metadata":{"Uri":"https://wamsamsclus001rest-hs.cloudapp.net/api/Assets('nb%3acid%3aUUID%3ad037b321-cd1c-43a9-9607-c4910fa7a85b')"}}],"Tasks":[{"Configuration":"H264 Adaptive Bitrate MP4 Set 720p","MediaProcessorId":"nb:mpid:UUID:1b1da727-93ae-4e46-a8a1-268828765609","TaskBody":"<?xml version=\"1.0\"encoding=\"utf-8\"?><taskBody><inputAsset>JobInputAsset(0)</inputAsset><outputAsset>JobOutputAsset(0)</outputAsset></taskBody>"}]}
The bearer token works as I use it for other request.
But I get a bad request 400 with the followin error message:
{"error":{"code":"","message":{"lang":"en-US","value":"Parsing request content failed due to: Make sure to only use property names that are defined by the type"}}}
Can anyone spot the error.
Thank you for the help
Okay I got it to work. Needed a odata=verbose in my json/string content - like this:
var jobInJson = JsonConvert.SerializeObject(job);
json = new StringContent(jobInJson, Encoding.UTF8);//,
json.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;odata=verbose");
I tried this earlier however I got a error 500 but now it is working.