如何在iOS中将base64字符串发送到服务器?

时间:2018-04-25 05:39:56

标签: ios objective-c iphone base64 nsurlsession

我正在申请中,我必须将image发送到server,我正在尝试将Image发送给server,但作为回报我正在获得

  

BAD REQUEST 400

。请告诉我如何解决此错误。

此方法用于将图像转换为base64字符串

 NSData * imagedata = UIImageJPEGRepresentation(chosenImage, 0.5);

 NSString * base64String = [imagedata base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength

-(void)temp
{

      NSString * str=[self base64return];
    NSDictionary* jsonDict = @{

                               @"name": @"image_name",
                               @"img_data":str
                               };

    NSData * postData   = [NSJSONSerialization dataWithJSONObject:jsonDict
                                                          options:kNilOptions error:nil];


    NSURL * url=[NSURL URLWithString:@"http://xxxxxx/finalresult1"];

    NSMutableURLRequest *request=[[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:120.0];



    [request setHTTPMethod:@"POST"];

        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

    [request setHTTPBody:postData];

    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];

    NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
                                  {
                                      if (error == nil)
                                      {
                                          // Success
                                          NSLog(@"URL Session Task Succeeded: HTTP %ld", ((NSHTTPURLResponse*)response).statusCode);





                                          NSString * text = [[NSString alloc] initWithData: data encoding:
                                                             NSUTF8StringEncoding];
                                          NSLog(@"Data = %@",text);
                                          NSLog(@"erroer is %@",error);
                                      }
                                      else
                                      {
                                          // Failure
                                          NSLog(@"URL Session Task Failed: %@", [error localizedDescription]);
                                      }
                                  }];
    [task resume];

}

1 个答案:

答案 0 :(得分:1)

更改请求内容类型,使用:          [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];