无法从网址获得回复

时间:2016-10-17 09:16:39

标签: ios objective-c httpresponse

在Stack Overflow中提到一些问题后,我使用下面的方法来获取响应和响应代码。

    NSMutableURLRequest *NSRequest;
    NSRequest = [[NSMutableURLRequest alloc] init];
    [NSRequest setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@://%@:%@/auth",[[NSUserDefaults standardUserDefaults] stringForKey:@"mongoScheme"],[[NSUserDefaults standardUserDefaults] stringForKey:@"mongoHost"],[[NSUserDefaults standardUserDefaults] stringForKey:@"mongoPort"]]]];
    [NSRequest setHTTPMethod:@"GET"];
    [NSRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [NSRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];


    NSHTTPURLResponse *response = nil;
    NSData *returnData = [NSURLConnection sendSynchronousRequest:NSRequest returningResponse:&response error:nil];

    NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
    int code = [httpResponse statusCode];
    NSLog(@"%i",code);
    NSLog(@"%@",response);

但是我无法得到任何一个。

我查看了日志,发现responsenullstatusCode0

我怎么能得到这个?

3 个答案:

答案 0 :(得分:1)

警告:在iOS 9.0中不推荐使用'sendSynchronousRequest(_:returningResponse :)'所以请使用:

对于Objective-C

NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:"Your_URL"]
          completionHandler:^(NSData *data,
                              NSURLResponse *response,
                              NSError *error) {
            // handle response

  }] resume];

对于Swift,

var request = NSMutableURLRequest(URL: NSURL(string: "YOUR URL"))
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"

var params = ["username":"username", "password":"password"] as Dictionary<String, String>

var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
    println("Response: \(response)")})

task.resume()

答案 1 :(得分:0)

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSString *string = BaseURLString1;
NSString* encodedUrl = [string stringByAddingPercentEscapesUsingEncoding:
                            NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:encodedUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:encodedUrl parameters:nil error:nil];
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    if (error) {
          NSLog(@"Error: %@", error);
     } else {
           NSArray *dictValue=[[NSArray alloc] init];
           dictValue=[responseObject valueForKey:@"KEY"];
    }];
    [dataTask resume];

答案 2 :(得分:0)

在Objective-C中执行HTTP请求的选项可能有点令人生畏。一个对我有用的解决方案是使用NSMutableURLRequest

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"GET"];
[request setURL:[NSURL URLWithString:url]];

NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *responseCode = nil;

NSData *oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];

if([responseCode statusCode] != 200){
    NSLog(@"Error getting %@, HTTP status code %i", url, [responseCode statusCode]);
    return nil;
}

return [[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];