2

How can i port the following .net HttpWebRequest to objective-c?

I have been given code snippets from a colleague for a POST request in .net to a certain server, and was required to implement the same in iOs. Should i just use NSMutableURLRequest and NSURLConnection and their respective delegates or do something else?

below is the colleague's source snippets in 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 { }
}
RabinDev
  • 658
  • 3
  • 13
  • I have implemented using NSMutableURLRequest and NSURLConnection but alas, it does not exactly work: i get a response that is a cross-domain policy xml. My colleague says the server is for silverlight clients and that i should do a multi-part POST (?) or use a stream to do the POST. (?) – RabinDev Nov 01 '11 at 14:06

1 Answers1

2

Yes you can use NSURLRequest.

Have a look at the docs. I believe there is example code showing a post request.

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

Here are the full docs on how it all works.

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

UPDATE:

A newer project created by Mobiata is open source and MUCH simpler to use for HTTP requests.

https://github.com/mobiata/MBRequest

logancautrell
  • 8,762
  • 3
  • 39
  • 50