Unity开源库:UnityHTTP

发布于 2020-12-03  185 次阅读


简介

这是一款基于TCPClient的HTTP操作库,可以实现HTTP的get和post常用操作。当然unity自带的UnityWebRequest已经足够强大,不过多会一种方法也不坏。后面还会推荐一个unitywebsocket开源库。

地址

andyburke/UnityHTTP: A TcpClient-based HTTP library for Unity. (github.com)

基本使用

  1. 配合携程使用,判断request.isDone属性
    public IEnumerator SomeRoutine() {
       HTTP.Request someRequest = new HTTP.Request( "get", "http://someurl.com/somewhere" );
    someRequest.Send();
    
       while( !someRequest.isDone )
       {
           yield return null;
       }
    
       // parse some JSON, for example:
       JSONObject thing = new JSONObject( request.response.Text );
    }
    
  2. 传入响应回调方法
    someRequest.Send( ( request ) => {
       // parse some JSON, for example:
       JSONObject thing = new JSONObject( request.response.Text );
    });
    
  3. Post方法使用
    WWWForm form = new WWWForm();
    form.AddField( "something", "yo" );
    form.AddField( "otherthing", "hey" );
    
    HTTP.Request someRequest = new HTTP.Request( "post", "http://someurl.com/some/post/handler", form );
    someRequest.Send( ( request ) => {
       bool result = false;
       //下面的json操作,推荐使用json.net
       Hashtable thing = (Hashtable)JSON.JsonDecode( request.response.Text, ref result );
       if ( !result )
       {
           Debug.LogWarning( "Could not parse JSON response!" );
           return;
       }
    });
    

要勇猛精进,用进取心做事;要豁达恬淡,用平常心处世。