如何发送POST和GET请求?

时间:2011-10-06 10:34:55

标签: objective-c swift post get nsurlsession

我想将JSON发送到网址(POSTGET)。

NSMutableDictionary *JSONDict = [[NSMutableDictionary alloc] init];
[JSONDict setValue:"myValue" forKey:"myKey"];

NSData *JSONData = [NSJSONSerialization dataWithJSONObject:self options:kNilOptions error:nil];

我当前的请求代码无效。

NSMutableURLRequest *requestData = [[NSMutableURLRequest alloc] init];

[requestData setURL:[NSURL URLWithString:@"http://fake.url/"];];

[requestData setHTTPMethod:@"POST"];
[requestData setValue:postLength forHTTPHeaderField:@"Content-Length"];
[requestData setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[requestData setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[requestData setHTTPBody:postData];

使用ASIHTTPRequest 是可靠的答案。

4 个答案:

答案 0 :(得分:128)

在iOS中发送POSTGET请求非常简单;并且不需要额外的框架。


POST请求:

我们首先创建POST的{​​{1}}(我们要发送的内容)作为body,然后将其转换为NSString。< / p>

NSData

接下来,我们阅读了NSString *post = [NSString stringWithFormat:@"test=Message&this=isNotReal"]; NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 的{​​{1}},因此我们可以在请求中传递它。

postData

现在我们要发布内容,我们可以创建length,并添加NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest

postData

最后,我们可以发送请求,并通过创建新的NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setURL:[NSURL URLWithString:@"http://YourURL.com/FakeURL"]]; [request setHTTPMethod:@"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setHTTPBody:postData]; 来阅读回复:

let post = "test=Message&this=isNotReal"
let postData = post.data(using: String.Encoding.ascii, allowLossyConversion: true)

let postLength = String(postData!.count)

var request = URLRequest(url: URL(string: "http://YourURL.com/FakeURL/PARAMETERS")!)
request.httpMethod = "POST"
request.addValue(postLength, forHTTPHeaderField: "Content-Length")
request.httpBody = postData;

NSURLSession

NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; NSLog(@"Request reply: %@", requestReply); }] resume]; 请求:

对于let session = URLSession(configuration: .default) session.dataTask(with: request) {data, response, error in let requestReply = NSString(data: data!, encoding: String.Encoding.ascii.rawValue) print("Request reply: \(requestReply!)") }.resume() 请求,它基本上是相同的,只有没有 GETGET

HTTPBody

Content-Length

在旁注中,您可以通过将以下内容添加到NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setURL:[NSURL URLWithString:@"http://YourURL.com/FakeURL/PARAMETERS"]]; [request setHTTPMethod:@"GET"]; NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; NSLog(@"Request reply: %@", requestReply); }] resume]; 来添加var request = URLRequest(url: URL(string: "http://YourURL.com/FakeURL/PARAMETERS")!) request.httpMethod = "GET" let session = URLSession(configuration: .default) session.dataTask(with: request) {data, response, error in let requestReply = NSString(data: data!, encoding: String.Encoding.ascii.rawValue) print("Request reply: \(requestReply!)") }.resume() (以及其他数据)。服务器在请求时可能需要这样做,例如

Content-Type

也可以使用NSMutableURLRequest读取响应代码。

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

更新: [(NSHTTPURLResponse*)response statusCode] 已弃用来自(10.11)以及之后。

request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

答案 1 :(得分:3)

使用RestKit您可以发出简单的POST请求(有关详情,请参阅此GitHub页面)。

在头文件中导入RestKit

#import <RestKit/RestKit.h>

然后,您可以先创建一个新的RKRequest

RKRequest *MyRequest = [[RKRequest alloc] initWithURL:[[NSURL alloc] initWithString:@"http://myurl.com/FakeUrl/"]];

然后指定您要提出的请求类型(在本例中为POST请求)。

MyRequest.method = RKRequestMethodPOST;
MyRequest.HTTPBodyString = YourPostString;

然后在additionalHTTPHeaders中将您的请求设置为JSON。

MyRequest.additionalHTTPHeaders = [[NSDictionary alloc] initWithObjectsAndKeys:@"application/json", @"Content-Type", @"application/json", @"Accept", nil];

最后,您可以发送请求。

[MyRequest send];

此外,您可NSLog查看结果的请求。

RKResponse *Response = [MyRequest sendSynchronously];
NSLog(@"%@", Response.bodyAsString);

来源:RestKit.orgMe

答案 2 :(得分:1)

 -(void)postmethod
    {

        NSString * post =[NSString stringWithFormat:@"Email=%@&Password=%@",_txt_uname.text,_txt_pwd.text];

        NSData *postdata= [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
        NSString *postLength=[NSString stringWithFormat:@"%lu",(unsigned long)[postdata length]];
        NSMutableURLRequest *request= [[NSMutableURLRequest alloc]init];

        NSLog(@"%@",app.mainurl);

       // NSString *str=[NSString stringWithFormat:@"%@Auth/Login",app.mainurl];
        NSString *str=YOUR URL;
        [request setURL:[NSURL URLWithString:str]];
        [request setHTTPMethod:@"POST"];
        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:postdata];
        NSError *error;
        NSURLResponse *response;

        NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
        NSString *returnstring=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
        NSMutableDictionary *dict=[returnstring JSONValue];

        NSLog(@"%@",dict);

        }

-(void)GETMethod
{
NSString *appurl;
    NSString *temp =@"YOUR URL";
    appurl = [NSString stringWithFormat:@"%@uid=%@&cid=%ld",temp,user_id,(long)clubeid];
    appurl = [appurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:appurl]];
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse: nil error: nil ];
    NSString  *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
    NSMutableDictionary *dict_eventalldata=[returnString JSONValue];
    NSString *success=[dict_eventalldata objectForKey:@"success"];
}

答案 3 :(得分:-1)

获取请求:

-(void)fetchData{

 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSData* data = [NSData dataWithContentsOfURL:[NSURL
                                                      URLWithString:@"yourURL"]];
        NSLog(@"LatestURL:%@",data);
        NSError* error=nil;
        NSDictionary *jsonDict= [NSJSONSerialization JSONObjectWithData:data
                                                                options:kNilOptions error:&error];
        NSLog(@"JSON = %@", [[NSString alloc] initWithData:data encoding:
                             NSUTF8StringEncoding]);
        dispatch_async(dispatch_get_main_queue(), ^{


    NSDictionary *statuses=[jsonDict objectForKey:@"result"];
    NSLog(@"SomeStatus :%@",statuses);

    if (!statuses)
    {
        NSLog(@"Error in Json :%@",error);
    }
    else
    {
        [self.arrayTimeline removeAllObjects];
        for(NSDictionary *newValu in statuses)
        {
            [self.arrayTimeline addObject:newValu];
            NSString *ProjectName=[newValu objectForKey:@"project_name"];
            NSLog(@"Project Name : %@",ProjectName);
            NSString *Stage=[newValu objectForKey:@"stage_name"];
            NSLog(@"Stage : %@",Stage);
            NSString *CompTime=[newValu objectForKey:@"completion_time"];
            NSLog(@"Completion Time : %@",CompTime);
            NSString *Status=[newValu objectForKey:@"status"];
            NSLog(@"Status : %@",Status);
        }
        [self.projectTimelineTable reloadData];
    });
} }); }

JSON响应: {&#34;状态&#34;:&#34;成功&#34;&#34;名称&#34;:&#34; PROJECT1&#34;&#34;地址&#34;:&#34; badkal mor地铁站&#34;,&#34;州&#34;:&#34; haryana&#34;,&#34; city&#34;:&#34; faridabad&#34;,&#34; start_time&# 34;:&#34; 1480586013&#34;,&#34; current_stage&#34;:&#34;招标接受&#34;,&#34;经理&#34;:&#34;不可用&#34;, &#34; completion_time&#34;:&#34; 1480464000&#34;}

您可以获取名称,start_time等键值并在标签上显示