用上面的方法再写一个http请求
时间: 2024-05-18 08:12:57 浏览: 11
好的,这里提供一个POST请求的示例代码:
```
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using UnityEngine;
using LitJson;
public class HttpHelper
{
private string baseUrl = "https://jsonplaceholder.typicode.com/";
public IEnumerator PostRequest(string path, Dictionary<string, string> parameters, System.Action<JsonData> callback)
{
// 创建请求对象
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseUrl + path);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// 设置请求参数
StringBuilder data = new StringBuilder();
foreach (KeyValuePair<string, string> pair in parameters)
{
data.AppendFormat("{0}={1}&", pair.Key, pair.Value);
}
byte[] byteData = Encoding.UTF8.GetBytes(data.ToString().TrimEnd('&'));
// 发送请求
request.ContentLength = byteData.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(byteData, 0, byteData.Length);
requestStream.Close();
// 获取响应
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
string responseText = reader.ReadToEnd();
reader.Close();
responseStream.Close();
// 解析响应数据
JsonData jsonData = JsonMapper.ToObject(responseText);
// 调用回调函数
callback(jsonData);
yield break;
}
}
```
这个示例代码实现了一个POST请求的功能,包含如下步骤:
1. 创建HttpWebRequest对象,并设置请求方法为POST和请求内容类型为application/x-www-form-urlencoded;
2. 将请求参数组装成字符串,并将其转换为字节数组,设置请求内容长度并将请求数据写入请求流中;
3. 使用GetResponse方法获取到HttpWebResponse对象,并从响应流中读取响应数据;
4. 使用LitJson库将响应数据解析为JsonData对象;
5. 调用回调函数,并将JsonData对象作为参数传入。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)