如何发送POST和GET请求? [英] How to send POST and GET request?

查看:132
本文介绍了如何发送POST和GET请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将我的 JSON 发送到一个URL( POST GET < code $)。

  NSMutableDictionary * JSONDict = [[NSMutableDictionary alloc] init]; 
[JSONDict setValue:myValueforKey:myKey];

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






我当前的请求代码不起作用。 / p>

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

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

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






使用 ASIHTTPRequest 不是是一个可靠的答案。 发送在iOS中POST GET 请求非常简单;并且不需要额外的框架。






POST 请求:



我们首先创建我们的 POST body (我们想要发送的)作为 NSString ,并将其转换为 NSData 显示问题标记为'objective-c''rel =标记标记为b

objective-c

  NSString * post = [NSString stringWithFormat:@test = Message& this = isNotReal ]; 
NSData * postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

接下来,我们读取 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];

swift

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

let postLength = String(postData!.count)

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

最后,我们可以发送我们的请求,并通过创建一个新的 NSURLSession



objective-c 的问题

  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(@请求回复:%@,requestReply);
}] resume];

swift


$ b

  let session = URLSession(configuration: 
session.dataTask(with:request){data,response,error in
let requestReply = NSString(data:data !, encoding:String.Encoding.ascii.rawValue)
print(Request reply:\(requestReply!))
} .resume()



< hr>

GET 请求:



使用 GET 请求它基本上是一样的,只有没有 HTTPBody Content-长度



objective-c

  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(@请求回复:%@,requestReply);
}] resume];

swift
$ b

  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,
let requestReply = NSString(data:data !, encoding:String.Encoding.ascii.rawValue)
print(Request回复:\(requestReply!))
.resume()






在附注中,您可以添加 Content-Type (和其他数据)到 NSMutableURLRequest 。这可能是服务器在请求时需要的,例如 json

objective-c

  [request setValue:@application / jsonforHTTPHeaderField :@内容类型]; 
[request setValue:@application / jsonforHTTPHeaderField:@Accept];

响应代码也可以使用 [(NSHTTPURLResponse *)response statusCode] 。



swift

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






更新: sendSynchronousRequest 弃用 from ios9 osx-elcapitan (10.11)和out。

  NSURLResponse * requestResponse; NSData * requestHandler = [NSURLConnection sendSynchronousRequest:request returningResponse:& requestResponse error:nil]; NSString * requestReply = [[NSString alloc] initWithBytes:[requestHandler bytes] length:[requestHandler length] encoding:NSASCIIStringEncoding]; NSLog(@requestReply:%@,requestReply); 


I want to send my JSON to a URL (POST and GET).

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

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


My current request code isn't working.

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];


Using ASIHTTPRequest is not a liable answer.

解决方案

Sending POST and GET requests in iOS is quite easy; and there's no need for an additional framework.


POST Request:

We begin by creating our POST's body (ergo. what we'd like to send) as an NSString, and converting it to NSData.

NSString *post = [NSString stringWithFormat:@"test=Message&this=isNotReal"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

Next up, we read the postData's length, so we can pass it along in the request.

NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

Now that we have what we'd like to post, we can create an NSMutableURLRequest, and include our 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;

And finally, we can send our request, and read the reply by creating a new 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()


GET Request:

With the GET request it's basically the same thing, only without the HTTPBody and 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()


On a side note, you can add Content-Type (and other data) by adding the following to our NSMutableURLRequest. This might be required by the server when requesting, e.g, a .

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

Response code can also be read using [(NSHTTPURLResponse*)response statusCode].

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


Update: sendSynchronousRequest is deprecated from and (10.11) and out.

NSURLResponse *requestResponse; NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request returningResponse:&requestResponse error:nil]; NSString *requestReply = [[NSString alloc] initWithBytes:[requestHandler bytes] length:[requestHandler length] encoding:NSASCIIStringEncoding]; NSLog(@"requestReply: %@", requestReply);

这篇关于如何发送POST和GET请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆