8

Basically I want to set

Content-Type: application/json;

in order to call a dot net web service and have it return json to an iphone application.

At the moment I have

NSString * jsonres = [[NSString alloc] initWithContentsOfURL:url];

What do I need instead in order to issue a blocking request ?

Andiih
  • 12,285
  • 10
  • 57
  • 88

1 Answers1

15

You need to use NSURLMutableRequest, here you can add headers for content-type and the sort, here is a r eference, http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSMutableURLRequest_Class/Reference/Reference.html#//apple_ref/occ/cl/NSMutableURLRequest, once you set up your request you can add the value using this method - (void)addValue:(NSString *)value forHTTPHeaderField:(NSString *)field something like

[request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
Leena
  • 2,678
  • 1
  • 30
  • 43
Daniel
  • 22,363
  • 9
  • 64
  • 71
  • Yep, I think that will do it. Thanks for the quick response! – Andiih Aug 24 '09 at 18:43
  • 1
    although its not a blocking style request, instead using delgates and callbacks - which will involve some re-architecting! – Andiih Aug 24 '09 at 19:11
  • for blokcing style you just gotta do an sync call (forgot to mention this sorry) you can use NSURLConnections method called + (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error, heres a link http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html#//apple_ref/occ/clm/NSURLConnection/sendSynchronousRequest:returningResponse:error: – Daniel Aug 24 '09 at 19:20
  • Thanks. Just figured that out myself and came back here to change my comments :-) You got there 5 hours ago! – Andiih Aug 25 '09 at 00:29
  • 1
    Please don't use sendSynchronousRequest from the main thread. It results in apps that perform poorly. – rpetrich Aug 25 '09 at 01:34
  • I think the syntax may have changed from addValue to setValue, but I'm not an expert on Objective C. Someone who knows more than me should verify that the API changed. `[request setValue:@"json" forHTTPHeaderField:@"Content-type"]`. This works for me, but perhaps there's something I'm missing; hence, I didn't edit your post. Also, forHTTPHeaderField may be misspelled. I suspect there are some syntax issues here even though this information is *very* helpful! :) – jamesmortensen May 21 '13 at 20:53
  • Then again sendSynchronousRequest has been deprecated for a while now. See http://stackoverflow.com/questions/21198404/nsurlsession-with-nsblockoperation-and-queues for the NSURLSession equivalent. – duncanwilcox Aug 14 '16 at 09:57