Skip to content

Commit 865dd48

Browse files
committed
POST!
POST json data + example
1 parent 0b3b148 commit 865dd48

File tree

7 files changed

+100
-30
lines changed

7 files changed

+100
-30
lines changed

Assets/HttpMono/HttpMono.cs

Lines changed: 54 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,20 @@
66

77
namespace HttpMono
88
{
9+
public static class UnityWebRequestExtensions
10+
{
11+
public static void AddHeaders(this UnityWebRequest webRequest, Dictionary<string, string> headers)
12+
{
13+
if (headers != null)
14+
{
15+
foreach (var h in headers)
16+
{
17+
webRequest.SetRequestHeader(h.Key, h.Value);
18+
}
19+
}
20+
}
21+
}
22+
923
public class HttpMono : MonoBehaviour
1024
{
1125

@@ -14,19 +28,13 @@ public void Get(string uri, Dictionary<string, string> headers = null, Action<Ht
1428
StartCoroutine(HttpGet(uri, headers, resultCallback));
1529
}
1630

17-
public IEnumerator HttpGet(string uri, Dictionary<string, string> headers = null, Action<HttpRequestResult> resultCallback = null)
31+
public IEnumerator HttpGet(string url, Dictionary<string, string> headers = null, Action<HttpRequestResult> resultCallback = null)
1832
{
19-
Debug.Log("GET: " + uri);
33+
Debug.Log("GET: " + url);
2034

21-
using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))
35+
using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
2236
{
23-
if (headers != null)
24-
{
25-
foreach (var h in headers)
26-
{
27-
webRequest.SetRequestHeader(h.Key, h.Value);
28-
}
29-
}
37+
webRequest.AddHeaders(headers);
3038

3139
// Request and wait for the desired page.
3240
yield return webRequest.SendWebRequest();
@@ -38,11 +46,47 @@ public IEnumerator HttpGet(string uri, Dictionary<string, string> headers = null
3846
}
3947

4048
resultCallback?.Invoke(result);
49+
}
50+
}
4151

52+
public void Post(string url, string postData, Dictionary<string, string> headers = null, Action<HttpRequestResult> resultCallback = null)
53+
{
54+
StartCoroutine(HttpPost(url, postData, headers, resultCallback));
55+
}
4256

57+
public IEnumerator HttpPost(string url, string postData, Dictionary<string, string> headers = null, Action<HttpRequestResult> resultCallback = null)
58+
{
59+
Debug.Log("POST: " + url);
4360

61+
Debug.Log("BODY: " + postData);
62+
63+
using (UnityWebRequest webRequest = new UnityWebRequest(url, "POST"))
64+
{
65+
webRequest.AddHeaders(headers);
66+
webRequest.SetRequestHeader("Content-Type", "application/json");
67+
webRequest.downloadHandler = new DownloadHandlerBuffer();
68+
69+
UploadHandler jsonUploadHandler = new UploadHandlerRaw(System.Text.Encoding.UTF8.GetBytes(postData));
70+
jsonUploadHandler.contentType = "application/json";
71+
webRequest.uploadHandler = jsonUploadHandler;
72+
73+
// Request and wait for the desired page.
74+
yield return webRequest.SendWebRequest();
75+
var result = new HttpRequestResult(webRequest);
76+
77+
if (result.Ok == false)
78+
{
79+
Debug.LogError(result.Error.Message);
80+
}
81+
if(result.HasText)
82+
{
83+
Debug.Log(result.Text);
84+
}
85+
86+
resultCallback?.Invoke(result);
4487
}
4588
}
4689

90+
4791
}
4892
}

Assets/HttpMono/HttpRequestResult.cs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ namespace HttpMono
99
public class HttpRequestResult
1010
{
1111
public bool Ok { get; }
12+
public bool HasText { get; }
1213
public HttpResultError Error { get; }
1314
public KeyValuePair<long, string> HttpCodeResponse { get; }
1415
public string Text { get; }
@@ -28,12 +29,15 @@ public HttpRequestResult(UnityWebRequest r)
2829
if (!Ok)
2930
{
3031
Error = new HttpResultError(r);
31-
return;
3232
}
3333

3434
if (r.downloadHandler != null)
3535
{
36-
Text = r.downloadHandler.text;
36+
if (string.IsNullOrEmpty(r.downloadHandler.text) == false)
37+
{
38+
HasText = true;
39+
Text = r.downloadHandler.text;
40+
}
3741
}
3842
}
3943
}

Assets/PetStore/PetshopConsumeExample.cs

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ public class PetshopConsumeExample : MonoBehaviour
1717
[SerializeField] string petIdToGet = "5";
1818

1919
[Header("New pet")]
20-
[SerializeField] NewPet newPet;
20+
[SerializeField] NewPet newPet = null;
2121

2222
[ContextMenu("Get Pets")]
2323
public void GetPets()
@@ -30,7 +30,7 @@ public void GetPets()
3030
{
3131
pets.ForEach(pet =>
3232
{
33-
Debug.Log("Pet ID: " + pet.Id + ", type: " + pet.Type + ", price: " + pet.Price);
33+
Debug.Log("Pet ID: " + pet.id + ", type: " + pet.type + ", price: " + pet.price);
3434
});
3535
});
3636
}
@@ -43,7 +43,7 @@ public void GetPet()
4343

4444
pet.ExecuteOperation<Pet>(operation, pet =>
4545
{
46-
Debug.Log("Pet ID: " + pet.Id + ", type: " + pet.Type + ", price: " + pet.Price);
46+
Debug.Log("Pet ID: " + pet.id + ", type: " + pet.type + ", price: " + pet.price);
4747
});
4848
}
4949

@@ -54,9 +54,10 @@ public void CreatePet()
5454
var serialized = JsonConvert.SerializeObject(newPet);
5555
operation.SetRequestBody(serialized);
5656

57-
pets.ExecuteOperation<Pet>(operation, pet =>
57+
pets.ExecuteOperation<NewPetResponse>(operation, r =>
5858
{
59-
Debug.Log("Pet ID: " + pet.Id + ", type: " + pet.Type + ", price: " + pet.Price);
59+
var pet = r.pet;
60+
Debug.Log("Pet name: " + pet.name + ", type: " + pet.type + ", price: " + pet.price);
6061
});
6162
}
6263
}

Assets/PetStore/_pets.asset

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ MonoBehaviour:
7878
IsLocal: 0
7979
Reference:
8080
UnresolvedReference: 0
81-
value:
81+
value: cat
8282
- parameter:
8383
Name: limit
8484
Required: 0
@@ -97,7 +97,10 @@ MonoBehaviour:
9797
IsLocal: 0
9898
Reference:
9999
UnresolvedReference: 0
100-
value:
100+
value: 3
101+
ExternalDocs:
102+
Description:
103+
Url:
101104
Description: 'Returns all pets from the system that the user has access to
102105
103106
Nam sed condimentum est. Maecenas tempor sagittis sapien, nec rhoncus sem sagittis
@@ -133,9 +136,12 @@ MonoBehaviour:
133136
RequestBody:
134137
Description: Pet to add to the store
135138
Required: 1
136-
LastRequestBody:
139+
LastRequestBody: '{"name":"Birdy","type":"bird","price":157.0}'
137140
Parameters: []
138141
ParametersValues: []
142+
ExternalDocs:
143+
Description:
144+
Url:
139145
Description: Creates a new pet in the store. Duplicates are allowed
140146
Summary:
141147
Tags: []

Assets/PetStore/data_model/Pet.cs

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
using System;
1+
using Newtonsoft.Json;
2+
using Newtonsoft.Json.Converters;
3+
using System;
24
using System.Collections;
35
using System.Collections.Generic;
46
using UnityEngine;
@@ -8,17 +10,25 @@ namespace PetStore
810
[Serializable]
911
public class Pet
1012
{
11-
public int Id;
12-
public PetType Type;
13-
public float Price;
13+
public int id;
14+
public PetType type;
15+
public float price;
1416
}
1517

1618
[Serializable]
1719
public class NewPet
1820
{
19-
public string Name;
20-
public PetType Type;
21-
public float Price;
21+
public string name;
22+
[JsonConverter(typeof(StringEnumConverter))]
23+
public PetType type;
24+
public float price;
25+
}
26+
27+
[Serializable]
28+
public class NewPetResponse
29+
{
30+
public NewPet pet;
31+
public string message;
2232
}
2333

2434
[Serializable]

Assets/Scenes/ApiTesting.unity

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -190,9 +190,9 @@ MonoBehaviour:
190190
pet: {fileID: 11400000, guid: 86e050ea5e7107a4c99652da82e45aa4, type: 2}
191191
petIdToGet: 5
192192
newPet:
193-
Name: Birdy
194-
Type: 3
195-
Price: 0
193+
name: Birdy
194+
type: 3
195+
price: 157
196196
--- !u!4 &929404285
197197
Transform:
198198
m_ObjectHideFlags: 0

Assets/UnityOpenApi/OpenApiAssets/ApiAsset.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,11 @@ internal void ExecutePathOperation(OAOperation operation, Action<HttpRequestResu
7777
case AOOperationType.Put:
7878
break;
7979
case AOOperationType.Post:
80+
if(operation.RequestBody.Required && string.IsNullOrEmpty(operation.RequestBody.LastRequestBody))
81+
{
82+
throw new Exception("Missing request body");
83+
}
84+
Http.HttpMono.Post(url, operation.RequestBody.LastRequestBody, headerParams, response);
8085
break;
8186
case AOOperationType.Delete:
8287
break;

0 commit comments

Comments
 (0)