【关于post的测试】

1、发起请求示例:
问题:
unity 写一段post请求到www.test.com的代码示例。
使用application/x-www-form-urlencoded (默)
application/xml
application/json
multipart/form-data,4种方式

代码示例:


```csharp
using UnityEngine;
using UnityEngine.Networking;

public class BaiduPostRequest : MonoBehaviour
{
    // 发送请求的URL
    private const string url = "https://www.test.com";

    // 用于application/x-www-form-urlencoded的内容
    private const string urlEncodedData = "name=Unity&age=123";

    // 用于application/xml的内容
    private const string xmlData = "<root><name>Unity</name><age>123</age></root>";

    // 用于application/json的内容
    private const string jsonData = "{\"name\":\"Unity\",\"age\":123}";

    // 用于multipart/form-data的内容
    private const string formData = "name=Unity&age=123";

    void Start()
    {
        // 使用application/x-www-form-urlencoded发送请求
        SendRequest("application/x-www-form-urlencoded", urlEncodedData);

        // 使用application/xml发送请求
        SendRequest("application/xml", xmlData);

        // 使用application/json发送请求
        SendRequest("application/json", jsonData);

        // 使用multipart/form-data发送请求
        SendRequest("multipart/form-data", formData);
    }

    void SendRequest(string contentType, string data)
    {
        // 创建一个新的UnityWebRequest
        UnityWebRequest request = new UnityWebRequest(url, "POST")
        {
            downloadHandler = new DownloadHandlerBuffer(),
            uploadHandler = new UploadHandlerRaw(data),
            headers = { "Content-Type" = contentType }
        };

        // 发送请求
        request.SendWebRequest().completed += (response) =>
        {
            // 打印响应内容
            Debug.Log(response.downloadHandler.text);
        };
    }
}

2.1、php接收请求示例
问题:
php接收post请求的的代码示例,要包含接收
application/x-www-form-urlencoded (默)
application/xml
application/json
multipart/form-data,4种方式

代码示例:

<?php

// 用于存储上传的文件
$uploads = [];

// 用于存储表单数据
$formData = [];

// 用于存储JSON数据
$jsonData = [];

// 用于存储XML数据
$xmlData = [];

// 模拟HTTP请求
$fakeRequest = [
    'name' => 'Unity',
    'age' => 123,
    'file' => ['name' => 'example.txt', 'content' => 'Hello World!']
];

// 模拟文件上传
$uploads['file'] = [
    'name' => 'example.txt',
    'content' => 'Hello World!',
    'type' => 'text/plain'
];

// 模拟application/x-www-form-urlencoded请求
$urlEncodedData = http_build_query($fakeRequest);

// 模拟application/xml请求
$xmlData = "<root><name>{$fakeRequest['name']}</name><age>{$fakeRequest['age']}</age></root>";

// 模拟application/json请求
$jsonData = json_encode($fakeRequest);

// 模拟multipart/form-data请求
$formData = $fakeRequest;
$formData['file'] = $uploads;

// 处理HTTP请求
switch ($_SERVER['HTTP_CONTENT_TYPE']) {
    case 'application/x-www-form-urlencoded':
        // 处理表单数据
        foreach ($_POST as $key => $value) {
            $formData[$key] = $value;
        }
        break;
    case 'application/xml':
        // 解析XML数据
        $xml = simplexml_load_string(file_get_contents('php://input'));
        foreach ($xml as $key => $value) {
            $xmlData[$key] = (string)$value;
        }
        break;
    case 'application/json':
        // 解析JSON数据
        $json = json_decode(file_get_contents('php://input'), true);
        foreach ($json as $key => $value) {
            $jsonData[$key] = $value;
        }
        break;
    case 'multipart/form-data':
        // 处理文件上传和表单数据
        foreach ($_FILES as $key => $value) {
            $uploads[$key] = $value;
        }
        foreach ($_POST as $key => $value) {
            $formData[$key] = $value;
        }
        break;
    default:
        // 未知的Content-Type
        exit('Unknown Content-Type');
}

// 打印接收到的数据
echo "Form Data:\n";
print_r($formData);
echo "JSON Data:\n";
print_r($jsonData);
echo "XML Data:\n";
print_r($xmlData);
echo "Uploads:\n";
print_r($uploads);

?>

2.2、go接收请求示例
问题:
go接收post请求的的代码示例,要包含接收
application/x-www-form-urlencoded (默)
application/xml
application/json
multipart/form-data,4种方式

代码示例:

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/httputil"
	"net/url"
)

func main() {
	http.HandleFunc("/", handleRequest)
	http.ListenAndServe(":8080", nil)
}

func handleRequest(w http.ResponseWriter, r *http.Request) {
	switch r.Header.Get("Content-Type") {
	case "application/x-www-form-urlencoded":
		handleForm(w, r)
	case "application/xml":
		handleXML(w, r)
	case "application/json":
		handleJSON(w, r)
	case "multipart/form-data":
		handleMultipartFile(w, r)
	default:
		http.Error(w, "Unsupported Media Type", http.StatusUnsupportedMediaType)
		return
	}
}

func handleForm(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		http.Error(w, "Method is not supported.", http.StatusNotFound)
		return
	}

	body := r.Body
	defer body.Close()

	formData := make(map[string][]string)
	if err := r.ParseForm(); err != nil {
		http.Error(w, "Error parsing form data", http.StatusInternalServerError)
		return
	}

	for key, values := range formData {
		fmt.Fprintf(w, "%s: %v\n", key, values)
	}
}

func handleXML(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		http.Error(w, "Method is not supported.", http.StatusNotFound)
		return
	}

	body := r.Body
	defer body.Close()

	xmlData, err := ioutil.ReadAll(body)
	if err != nil {
		http.Error(w, "Error reading XML data", http.StatusInternalServerError)
		return
	}

	fmt.Fprintf(w, "Received XML: %s\n", xmlData)
}

func handleJSON(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		http.Error(w, "Method is not supported.", http.StatusNotFound)
		return
	}

	body := r.Body
	defer body.Close()

	jsonData, err := ioutil.ReadAll(body)
	if err != nil {
		http.Error(w, "Error reading JSON data", http.StatusInternalServerError)
		return
	}

	var data map[string]interface{}
	if err := json.Unmarshal(jsonData, &data); err != nil {
		http.Error(w, "Error unmarshalling JSON data", http.StatusInternalServerError)
		return
	}

	fmt.Fprintf(w, "Received JSON: %v\n", data)
}

func handleMultipartFile(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		http.Error(w, "Method is not supported.", http.StatusNotFound)
		return
	}

	body := r.Body
	defer body.Close()

<formData := make(map[string][]string)
files := make(map[string]url.Values)

if err := r.ParseMultipartForm(10 << 20); err != nil {
	http.Error(w, "Error parsing multipart form data", http.StatusInternalServerError)
	return
}

for key, value := range formData {
		fmt.Fprintf(w, "%s: %v\n", key, value)
	}

for key, file := range files {
		fmt.Fprintf(w, "%s: %v\n", key, file)
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值