一种团结iOS的HTTP请求方法?(A method for making HTTP request

2019-06-27 15:57发布

我需要发送与所有标准的RESTful方法和访问请求的主体的HTTP请求,以便发送/它接收JSON。 我进去看了看,

WebRequest.HttpWebRequest

这工作几乎完美,但有些情况下,例如,如果服务器停机功能的GetResponse可能需要几秒钟到return-,因为它是一个同步的方法 - 冷冻该期间的应用案例。 这种方法,BeginGetResponse的异步版本,似乎并没有异步工作(在Unity反正),因为它仍然冻结该期间的应用。

UnityEngine.WWW#

仅支持POST和GET一些reason-请求,但我还需要PUT和DELETE(标准的RESTful方法),所以我没有打扰寻找到它的任何进一步。

的System.Threading

为了不结冰我看着使用线程的应用程序运行WebRequest.HttpWebRequest.GetResponse。 线程似乎在编辑器中工作(但显得格外volatile-如果应用程序退出时它一直在编辑器中运行,甚至永远当你停止它不停止线程),当尽快建成iOS设备崩溃它当我试图启动一个线程(我忘了写下来的错误,我没有访问它现在)。

与桥梁,以统一的应用程序运行在原生iOS应用线程

可笑,甚至没有去尝试这个。

UniWeb

这个。 我想知道他们是怎么做的。

这里是WebRequest.BeginGetResponse方法,我想的一个例子,

// The RequestState class passes data across async calls.
public class RequestState
{
   const int BufferSize = 1024;
   public StringBuilder RequestData;
   public byte[] BufferRead;
   public WebRequest Request;
   public Stream ResponseStream;
   // Create Decoder for appropriate enconding type.
   public Decoder StreamDecode = Encoding.UTF8.GetDecoder();

   public RequestState()
   {
      BufferRead = new byte[BufferSize];
      RequestData = new StringBuilder(String.Empty);
      Request = null;
      ResponseStream = null;
   }     
}

public class WebRequester
{
    private void ExecuteRequest()
    {
        RequestState requestState = new RequestState();
        WebRequest request = WebRequest.Create("mysite");
        request.BeginGetResponse(new AsyncCallback(Callback), requestState);
    }

    private void Callback(IAsyncResult ar)
    {
      // Get the RequestState object from the async result.
      RequestState rs = (RequestState) ar.AsyncState;

      // Get the WebRequest from RequestState.
      WebRequest req = rs.Request;

      // Call EndGetResponse, which produces the WebResponse object
      //  that came from the request issued above.
      WebResponse resp = req.EndGetResponse(ar);
    }
}

......在此基础上: http://msdn.microsoft.com/en-us/library/86wf6409(v=vs.71).aspx

Answer 1:

好吧,我终于写我自己的解决方案 。 基本上,我们需要一个RequestState, 回调方法超时线程 。 在这里我就复制什么在UnifyCommunity做 (现在叫unity3d维基)。 这是过时的代码,但比那里的东西,这样比较方便在这里显示更小的东西。 现在我已经删除(在unit3d维基) System.Actionstatic的性能和简单:

用法

static public ThisClass Instance;
void Awake () {
    Instance = GetComponent<ThisClass>();
}
static private IEnumerator CheckAvailabilityNow () {
    bool foundURL;
    string checkThisURL = "http://www.example.com/index.html";
    yield return Instance.StartCoroutine(
        WebAsync.CheckForMissingURL(checkThisURL, value => foundURL = !value)
        );
    Debug.Log("Does "+ checkThisURL +" exist? "+ foundURL);
}

WebAsync.cs

using System;
using System.IO;
using System.Net;
using System.Threading;
using System.Collections;
using UnityEngine;

/// <summary>
///  The RequestState class passes data across async calls.
/// </summary>
public class RequestState
{
    public WebRequest webRequest;
    public string errorMessage;

    public RequestState ()
    {
        webRequest = null;
        errorMessage = null;
    }
}

public class WebAsync {
    const int TIMEOUT = 10; // seconds

    /// <summary>
    /// If the URLs returns 404 or connection is broken, it's missing. Else, we suppose it's fine.
    /// </summary>
    /// <param name='url'>
    /// A fully formated URL.
    /// </param>
    /// <param name='result'>
    /// This will bring 'true' if 404 or connection broken and 'false' for everything else.
    /// Use it as this, where "value" is a System sintaxe:
    /// value => your-bool-var = value
    /// </param>
    static public IEnumerator CheckForMissingURL (string url, System.Action<bool> result) {
        result(false);

        Uri httpSite = new Uri(url);
        WebRequest webRequest = WebRequest.Create(httpSite);

        // We need no more than HTTP's head
        webRequest.Method = "HEAD";
        RequestState requestState = new RequestState();

        // Put the request into the state object so it can be passed around
        requestState.webRequest = webRequest;

        // Do the actual async call here
        IAsyncResult asyncResult = (IAsyncResult) webRequest.BeginGetResponse(
            new AsyncCallback(RespCallback), requestState);

        // WebRequest timeout won't work in async calls, so we need this instead
        ThreadPool.RegisterWaitForSingleObject(
            asyncResult.AsyncWaitHandle,
            new WaitOrTimerCallback(ScanTimeoutCallback),
            requestState,
            (TIMEOUT *1000), // obviously because this is in miliseconds
            true
            );

        // Wait until the the call is completed
        while (!asyncResult.IsCompleted) { yield return null; }

        // Deal up with the results
        if (requestState.errorMessage != null) {
            if ( requestState.errorMessage.Contains("404") || requestState.errorMessage.Contains("NameResolutionFailure") ) {
                result(true);
            } else {
                Debug.LogWarning("[WebAsync] Error trying to verify if URL '"+ url +"' exists: "+ requestState.errorMessage);
            }
        }
    }

    static private void RespCallback (IAsyncResult asyncResult) {

        RequestState requestState = (RequestState) asyncResult.AsyncState;
        WebRequest webRequest = requestState.webRequest;

        try {
            webRequest.EndGetResponse(asyncResult);
        } catch (WebException webException) {
            requestState.errorMessage = webException.Message;
        }
    }

    static private void ScanTimeoutCallback (object state, bool timedOut)  { 
        if (timedOut)  {
            RequestState requestState = (RequestState)state;
            if (requestState != null) 
                requestState.webRequest.Abort();
        } else {
            RegisteredWaitHandle registeredWaitHandle = (RegisteredWaitHandle)state;
            if (registeredWaitHandle != null)
                registeredWaitHandle.Unregister(null);
        }
    }
}


Answer 2:

我线程对iOS-工作,我相信这是崩溃,由于鬼线什么的。 重新启动设备似乎有固定的崩溃,所以我就用WebRequest.HttpWebRequest与线程。



Answer 3:

有异步这样做的方式,不使用的IEnumerator和收益回报的东西。 退房eDriven框架。

HttpConnector类: https://github.com/dkozar/eDriven/blob/master/eDriven.Networking/Rpc/Core/HttpConnector.cs

我在这个Web播放演示使用了与JsonFX所有HttpConnector的时间,例如: http://edrivenunity.com/load-images

没有PUT和DELETE是不是一个大问题,因为这一切可以使用GET和POST来完成。 举例来说,我成功地使用Drupal的CMS的REST服务进行通信。



Answer 4:

// javascript in the web player not ios, android or desktop you could just run the following code:

var jscall:String;
    jscall="var reqScript = document.createElement('script');";
    jscall+="reqScript.src = 'synchmanager_secure2.jsp?userid="+uid+"&token="+access_token+"&rnd='+Math.random()*777;";
    jscall+="document.body.appendChild(reqScript);";
Application.ExternalEval(jscall);
// cs
string jscall;
    jscall="var reqScript = document.createElement('script');";
    jscall+="reqScript.src = 'synchmanager_secure2.jsp?userid="+uid+"&token="+access_token+"&rnd='+Math.random()*777;";
    jscall+="document.body.appendChild(reqScript);";
    Application.ExternalEval(jscall);

// then update your object using the your return in a function like this
// json return object always asynch
function sendMyReturn(args){
     var unity=getUnity();
     unity.SendMessage("object", "function", args );
}
sendMyReturn(args);

或者你可以用这个通过AJAX功能发送预先编写自定义标题为安全起见,你需要签署头和签名的请求从服务器返回我喜欢MD5签名比较他们没有那么大



文章来源: A method for making HTTP requests on Unity iOS?