Wun
Wun

Reputation: 6381

How to set http header for for HTTP in Objective-C?

I am trying to implement Http in IOS.

I use the following code to send GET command to the Server.

SERVER_IP        = @"xxx.xx.xxx.xxx";
PORT             = @"12345";
USER_ID             = @"1234-1234-1234-1234-1234";
USER_PWD             = @"123456";
url = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@:%@/message/user/%@",SERVER_IP,PORT,USER_ID]];

[request setHTTPMethod:@"GET"];
    request = [NSURLRequest requestWithURL:url];

    NSDictionary *header = [request allHTTPHeaderFields];
    [header setValue:@"Authorization" forKey:USER_PWD];

    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@",html);
    }];

It show **The resource requires authentication, which was not supplied with the request** at the log.

I have set the parameter header , but I don't know how to use it.

Can someone help me and teach me how to implement GET command and setting password?

Upvotes: 0

Views: 1340

Answers (4)

Mike Zriel
Mike Zriel

Reputation: 1865

Create an NSDictionary with all your header fields and use the following command to set the required headers.

NSDictionary *dictHeader = @{@"Content-Type": @"application/octet-stream", 
@"Authorization": @"accessToken"};

[request setAllHTTPHeaderFields:dictHeader];

Upvotes: 0

Daniele
Daniele

Reputation: 2469

You need to set the header on the NSURLRequest somehow, something like that will do.

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
[request setHTTPMethod:@"GET"];
[request setValue:USER_PWD forHTTPHeaderField:@"Authorization"];

Upvotes: 1

Mutawe
Mutawe

Reputation: 6524

Use the following:

[request setValue:@"xxx" forHTTPHeaderField:@"Content-Type"];

But you have to change the NSURLRequest to NSMutableURLRequest, please check Zaph's answer

Upvotes: 1

zaph
zaph

Reputation: 112857

The header information is added to the URLRequest.

Create a NSMutableURLRequest and use the setValue:forHTTPHeaderField: method to add the header to the request.

There are many other setting available for NSMutableURLRequest.

Upvotes: 1

Related Questions