How to use Unity WWW

concept

WWW is based on HTTP protocol, we can use it to send HTTP requests.
In general, there are two ways to request:

  1. Get request
  2. Post request

request type

Get request

The Get request will carry the data in the url, and can only transfer up to 1024 bytes.
Suppose we want to send to the specified url: http://dict.youdao.com/suggest

  • user (account) = 123
  • pwd (password) = 456
    then use it like this:
 要发送的url:"http://dict.youdao.com/suggest";
 携带数据后的url:"http://dict.youdao.com/suggest?user=123&pwd=456"
 WWW www = new WWW(url) 

You can see that the data is wrapped in the url, which is not very safe

Post request

For Post requests, the data can be carried by WWWFrom (similar to dictionary key-value pairs), or it can be converted into a binary stream. In this way, the data will not be carried in the url, which is more secure, and there is no data length limit.
It is probably used like this

  	WWWForm wwwForm = new WWWForm();
    wwwForm.AddField("user","123");
    wwwForm.AddField("pwd","456");
    WWW www = new WWW(url,wwwForm);

actual use

We talked about the concept earlier, let's use it in detail next.

function to be implemented

I found an API on the Internet that can look up words. The link is here . Next, we will use it to look up the word heart.

  • url = “http://dict.youdao.com/suggest”
    参数:
  • q = the word to look up;
  • doctype = the format to be returned, the default is xml;

Get request

    IEnumerator WWW_Get()
    {
    
    
        string url = "http://dict.youdao.com/suggest";
        string contentFormat = "?q={0}&doctype=json";
        string word = "heart";
        //拼接好最后的url
        string finalStr = url + string.Format(contentFormat, word);
        WWW www = new WWW(finalStr);
        yield return www;
        //如果error是空的,说明访问成功
        if (string.IsNullOrEmpty(www.error))
        {
    
    
            Debug.LogWarning($"success,content:{
      
      www.text}");
        }
        else
        {
    
    
            Debug.LogWarning($"failed,msg:{
      
      www.error}");
        }
    }

request result

success,content:{
    
    "result":{
    
    "msg":"success","code":200},"data":{
    
    "entries":[{
    
    "explain":"n. 心脏;感情;勇气;心形;要点; vt. 鼓励;铭记; vi. 结心; n. (Heart)人名...","entry":"heart"},{
    
    "explain":"adj. 衷心的;真诚的;真心真意的","entry":"heartfelt"},{
    
    "explain":"n. 灶台;炉边;炉床;壁炉地面; n. (Hearth)人名;(英)哈思","entry":"hearth"},{
    
    "explain":"adj. 衷心的;丰盛的;健壮的;精神饱满的; n. 朋友们;伙伴们","entry":"hearty"},{
    
    "explain":"n. 心跳;情感","entry":"heartbeat"}],"query":"heart","language":"en","type":"dict"}}

Post request

    IEnumerator WWW_Post_Form()
    {
    
    
        //https://www.free-api.com/doc/522
        WWWForm wwwForm = new WWWForm();
        wwwForm.AddField("q","heart");//设置要查询单词
        wwwForm.AddField("doctype","json");//设置返回的数据格式为json

        string url = "http://dict.youdao.com/suggest";

        WWW www = new WWW(url,wwwForm);
        yield return www;
        if (string.IsNullOrEmpty(www.error))
        {
    
    
            Debug.LogWarning($"success,content:{
      
      www.text}");
        }
        else
        {
    
    
            Debug.LogWarning($"failed,msg:{
      
      www.error}");
        }
    }

The returned result is the same as that of the Get request.

Headers header verification

The usage of Get/Post is described above, generally speaking, it is enough to use it like this. However, when sending a Post request, we are also allowed to add Headers header verification.
What is the function of this? This can be used to inform the server of the data format we transmit, for example, it can indicate that the data we transmit is in the default format or json format; after checking it online, it seems that some verification headers can also be added to prevent malicious access.

Generally speaking, this is an agreement with the server, and then it can be added according to the agreement.
Let's understand how to use it. Let's take a look at the construction method of www

public WWW(string url) //get请求可以使用
public WWW(string url, WWWForm form) //post请求,使用form携带数据
public WWW(string url, byte[] postData) //post请求,传递数据流
public WWW(string url, byte[] postData, Dictionary<string, string> headers)//post请求,允许携带hearders数据

The first method and the second method have been mentioned above.
The third method, passing binary data.
In fact, you can still use wwwForm to carry data like the second method. Finally, use wwwForm.data to get the binary stream, just pass it in.

The fourth method is the same as the third method, except that a dictionary parameter is added at the end to carry the verification data
Next, we will use the code of the fourth method

    IEnumerator WWW_Post_Bytes()
    {
    
    
        WWWForm wwwForm = new WWWForm();
        wwwForm.AddField("q","heart");
        wwwForm.AddField("doctype","json");

        string url = "http://dict.youdao.com/suggest";
        
        //这里添加headers字典
        Dictionary<string, string> postHeader = new Dictionary<string, string>();
        postHeader.Add("Content-Type", "application/x-www-form-urlencoded"); //默认
        // postHeader.Add("Content-Type", "application/json");//json
        
        WWW www = new WWW(url,wwwForm.data,postHeader);
        yield return www;
        if (string.IsNullOrEmpty(www.error))
        {
    
    
            Debug.LogWarning($"success,content:{
      
      www.text}");
        }
        else
        {
    
    
            Debug.LogWarning($"failed,msg:{
      
      www.error}");
        }
    }

In fact, it is a dictionary, and then the agreed data can be passed in~

Guess you like

Origin blog.csdn.net/aaa27987/article/details/121108050