【问题标题】:how can I send the array as a parameter to url using get request without afnetworking如何在没有afnetworking的情况下使用get请求将数组作为参数发送到url
【发布时间】:2018-02-14 10:48:25
【问题描述】:

我必须使用get请求将数组作为参数之一发送到url,url是http://13.229.45.226/api/resource/Employee/?filters=[["Employee", "company_email", "=", "susee@lektrify.club"]]。我正在使用 nsurl 会话进行 api 调用。

请找到以下代码

NSArray *myArray = @[@"Employee",@"company_email",@"=",Emailid];


NSData *json = [NSJSONSerialization dataWithJSONObject:myArray options:0 error:nil];

NSString *jsonString = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
NSLog(@"jsonData as string:\n%@", jsonString);

NSString *urlstr= [NSString stringWithFormat:@"http://xx.xxx.xx.xxx/api/resource/Employee/?filters=[\n%@]",jsonString];

 NSLog(@"%@",urlstr);

[apicall getDictionaryFromApiwithoutlogin:urlstr restfulType:kRestfulGet andUseContentType:NO withRequestBody:nil withheader:YES completionHandler:^(NSDictionary *result){
    dispatch_async(dispatch_get_main_queue(), ^{ }];

这是为在我提供输入的敌人中调用通用 api 编写的代码。

    -(void)getDictionaryFromApiwithoutlogin:(NSString *)url restfulType:(NSInteger)restfulType andUseContentType:(BOOL)useContentType withRequestBody:(NSData*)httpBody withheader:(BOOL)header completionHandler:(void (^)(NSDictionary *isSuccess))isSuccess
{

loginstatus = [[NSUserDefaults standardUserDefaults] boolForKey:@"loginStatus"];

    if (![APICall hasNetwork])
    {
        //  [customBezelActivityView removeViewAnimated:YES];
        // [Util displayToastMessage:@"No internet connection"];
        return;
    }

    /* RESTFUL request function, all API request will come here */
    //url  = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
url=[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSLog(@"url:%@",url);

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:300.0];
    // set request variables
    if (restfulType == kRestfulGet) {
        [request setHTTPMethod:@"GET"];
    } else if (restfulType == kRestfulPost) {
        [request setHTTPMethod:@"POST"];
    } else if (restfulType == kRestfulPut) {
        [request setHTTPMethod:@"PUT"];
    } else {
        [request setHTTPMethod:@"DELETE"];
    }

    if (useContentType) {
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    }
if (header) {
    [request setValue:[NSString stringWithFormat:@"Bearer %@",[[NSUserDefaults standardUserDefaults]valueForKey:@"access_token"]] forHTTPHeaderField:@"Authorization"];
}
    if (httpBody != nil) {
        request.HTTPBody = httpBody;
    }

    NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error == nil)
        {
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
            if ([httpResponse respondsToSelector:@selector(statusCode)])
            {
                NSInteger responseStatusCode = [httpResponse statusCode];
                NSLog(@"api response: %@", httpResponse);
                if (responseStatusCode == 200)
                {
                    NSDictionary *response = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
                    isSuccess(response);
                }else if (responseStatusCode==401)
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [customBezelActivityView removeViewAnimated:YES];

                        [APICall sigininpageafteraccestokenexperise];

                    });

                }
                else if (responseStatusCode==500)
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [customBezelActivityView removeViewAnimated:YES];


                        [[NSNotificationCenter defaultCenter]postNotificationName:@"usernotfound" object:nil];
                    });

                }

                else{
                    [customBezelActivityView removeViewAnimated:YES];
                    [APICall handleApiErrorCode:responseStatusCode];
                }
            }
        }else
            dispatch_async(dispatch_get_main_queue(), ^{
                [customBezelActivityView removeViewAnimated:YES];
                [Util handleErrorCodesForApi:(int)error.code];
            });
    }];
    [postDataTask resume];
    [session finishTasksAndInvalidate];


}

当我尝试在 post man 数组中链接这个 [["Employee", "company_email", "=", "xxx@xxx.club"]] 。它正在研究如何处理这个数组并添加到 url 并发出获取请求。

感谢您的快速响应。

【问题讨论】:

  • 你能告诉我你是如何在 Postman 中使用这个东西的吗?只需使用您的邮递员请求快照更新您的问题。
  • @ArunKumar 我找到了解决方案;感谢您的回复
  • 这个问题在网站上已经被问过很多次了,你应该先搜索一下再问一些关于SO的问题。
  • @SaadChaudhry 我没有从她那里找到答案,我是从我的朋友那里得到的

标签: ios objective-c arrays nsurlsession


【解决方案1】:

我找到了问题的解决方案

解决方案是你必须创建一个数组,你必须对数据和编码字符串进行 NSJSONSerialization 这解决了问题

NSArray *myArray = @[@"Employee",@"company_email",@"=",Emailid];

NSData *json = [NSJSONSerialization dataWithJSONObject:myArray options:0 error:nil];

NSString *jsonString = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
NSLog(@"jsonData as string:\n%@", jsonString);

NSString *urlstr= [NSString stringWithFormat:@"http://xx.xxx.xx.xxx/api/resource/Employee/?filters=[\n%@]",jsonString];

请查看更新后的问题以获得完整答案

【讨论】:

    【解决方案2】:

    您可以使用NSURLComponents 类从它们的组成部分构造 URL。

    在您的回答中,您是自己手动构建 queryString,一个参数可以,但如果您有多个参数,那么它会很忙。

    你的例子:

        NSURLComponents *urlComponents = [NSURLComponents componentsWithString:@"http://13.229.45.226/api/resource/Employee/"];
        NSURLQueryItem *item1 = [NSURLQueryItem queryItemWithName:@"filters" value:@"Employee"];
        NSURLQueryItem *item2 = [NSURLQueryItem queryItemWithName:@"company_email" value:@"susee@lektrify.club"];
        [urlComponents setQueryItems: @[item1,item2]];
        NSLog(@"%@",urlComponents.URL);
    

    输出:

    http://13.229.45.226/api/resource/Employee/?filters=Employee&company_email=susee@lektrify.club
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-15
      • 2013-08-22
      相关资源
      最近更新 更多