我如何将.net的HttpWebRequest移植到iOs的URLRequest

时间:2011-11-01 13:07:35

标签: c# .net objective-c ios nsurlrequest

如何将以下.net HttpWebRequest移植到objective-c?

我已经从同事处获得了.net中的POST请求到某个服务器的代码片段,并且需要在iOs中实现相同的代码片段。我应该只使用NSMutableURLRequest和NSURLConnection及其各自的代表或做其他事情吗?

下面是同事在C#中的源代码片段:

public void SendMessage(ref string Message)
{
   if (m_pURL == null) return;

   HttpWebRequest request = (HttpWebRequest)WebRequest.Create(m_pURL);
   request.Method = "POST";
   request.ContentLength = Message.Length;
   request.AllowWriteStreamBuffering = false;
   request.UseDefaultCredentials = true;

   RequestState request_state = new RequestState();
   request_state.Request = request;
   request_state.RequestData.Append(Message);
   request.BeginGetRequestStream(WriteCallBack, request_state);
   request = null;
}

private void WriteCallBack(IAsyncResult iar)
{
   try
   {
     RequestState request_state = (RequestState)iar.AsyncState;
     HttpWebRequest request = request_state.Request;
     Stream stream = request.EndGetRequestStream(iar);

     byte[] buffer = Encoding.UTF8.GetBytes(request_state.RequestData.ToString());
                    stream.Write(buffer, 0, buffer.Length);
                    stream.Close();
                    request.BeginGetResponse(getRequestResult => { },null);
   }
   catch { }
}

1 个答案:

答案 0 :(得分:2)

是的,您可以使用NSURLRequest。

看看文档。我相信有一个显示帖子请求的示例代码。

http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLRequest_Class/

以下是有关它如何运作的完整文档。

http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html#//apple_ref/doc/uid/10000165i

更新:

Mobiata创建的一个较新项目是开源的,并且可以更简单地用于HTTP请求。

https://github.com/mobiata/MBRequest