using System.Collections; using UnityEngine; using UnityEngine.Networking; using UnityEngine.UI; using LitJson; using System.Collections.Generic; public class GetData : MonoBehaviour { public Text resultText; IEnumerator Start() { // 定义接口地址和请求参数 string url = "http://158.58.50.21:8886/view/queryFaultAndSubhealthInfo"; string json = "{"lineid": 27, "areaid": 22, "starttime": "2023-05-07 09:54:22", "endtime": "2023-06-07 09:54:22", "datatype": 2, "pageSize": 5, "pageNumber": 1 }"; // 构造请求 UnityWebRequest request = new UnityWebRequest(url, "POST"); byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(json); request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw); request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer(); request.SetRequestHeader("Content-Type", "application/json"); // 发送请求 yield return request.SendWebRequest(); // 处理返回结果 if (request.isError) { Debug.Log(request.error); resultText.text = request.error; } else { // 解析返回的 JSON 数据 JsonData jsonData = JsonMapper.ToObject(request.downloadHandler.text); // 获取需要的数据,将其显示在文本框中 string text = ""; foreach (JsonData item in jsonData["data"]["list"]) { text += item["doorno"].ToString() + " - " + item["faultname"].ToString() + " - " + item["happentime"].ToString() + "\n"; } resultText.text = text; } } }将请求方式改为post,代码怎么写
时间: 2023-07-21 21:58:24 浏览: 130
Simple WWW http.rar
这段代码中已经将请求方式改为POST了,可以直接使用。如果你需要看一下使用GET方式的代码,可以参考下面的示例代码:
```
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
using LitJson;
using System.Collections.Generic;
public class GetData : MonoBehaviour {
public Text resultText;
IEnumerator Start() {
// 定义接口地址和请求参数
string url = "http://158.58.50.21:8886/view/queryFaultAndSubhealthInfo?lineid=27&areaid=22&starttime=2023-05-07 09:54:22&endtime=2023-06-07 09:54:22&datatype=2&pageSize=5&pageNumber=1";
// 构造请求
UnityWebRequest request = UnityWebRequest.Get(url);
// 发送请求
yield return request.SendWebRequest();
// 处理返回结果
if (request.isError) {
Debug.Log(request.error);
resultText.text = request.error;
}
else {
// 解析返回的 JSON 数据
JsonData jsonData = JsonMapper.ToObject(request.downloadHandler.text);
// 获取需要的数据,将其显示在文本框中
string text = "";
foreach (JsonData item in jsonData["data"]["list"]) {
text += item["doorno"].ToString() + " - " + item["faultname"].ToString() + " - " + item["happentime"].ToString() + "\n";
}
resultText.text = text;
}
}
}
```
使用GET方式时,请求参数是在URL中进行传递的,而不是在请求体中。需要修改的是URL中的参数,将其拼接在URL的后面即可。
阅读全文