使用“POST”方法从.net服务器到objective-c获取映像响应

时间:2016-01-11 09:28:41

标签: ios objective-c

很抱歉再次提出相同/相关的问题

今天早上我在Click here发了一个问题,我也得到了正确答案,我的问题也解决了。

在我的.net开发人员的同一案例中,创建了一个用于上传用户个人资料照片的API。我遵循相同的指导方针,我也做了代码

但是我收到了错误:

在这里,我发布了我的代码,如::

- (void)getLoginUserId:(NSString*)newUserId withUploadImageData: (NSString*)newImageData;
{
    NSString*urlStr =  @"http://taxi.expertverification.com/api/v1/Getimage";
    NSString * myRequestString =[NSString stringWithFormat:@"user_id=%@&imageget=%@",
                             newUserId,
                             newImageData];
    NSData *myRequestData = [NSData dataWithBytes: [myRequestString UTF8String] length: [myRequestString length]];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlStr]];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
    [request setHTTPMethod: @"POST"];
    //post section
    [request setHTTPBody: myRequestData];
    NSURLSession *session = [NSURLSession sharedSession];
    [[session dataTaskWithRequest:request
            completionHandler:^(NSData *data,
                                NSURLResponse *response,
                                NSError *error) {
                // handle response
                NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
                NSLog(@"requestReply: %@", requestReply);
            }] resume];
}

调用方法是::

 [self getLoginUserId:@"121"
  withUploadImageData:@"iVBORw0KGgoAAAANSUhEUgAAAOYAAADmCAMAAAD2tAmJAAAAb1BMVEXb29v8/Pz+/v79/f37+/v6+vrx8fHy8vL5+fnz8/P19fX29vb09PTw8PD4+Pj39/f////v7+/u7u7t7e3s7Ozr6+vc3Nzi4uLn5+fq6urg4ODl5eXp6enj4+Pm5ube3t7f39/o6Ojh4eHd3d3k5OTu4Gi4AAAAHGlET1QAAAACAAAAAAAAAHMAAAAoAAAAcwAAAHMAAANJX1LtGgAAAxVJREFUeAHsm+t2okAQhHuTXS+gEmUB7xqT93/GGBezo7DkyFSxM0z3HwdI+vTXVXPRGHkJIi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chw59UyGf8s1VzPs9nQRs8G+6QZHy1+d2jTFh6lUt4ApP0ylXuPUpSl2/TPsHNeXOHVM4cPsA5vMMYXPmc9IX+ZOTZqCzv48SbrbYhinhinifKUONnpuuESYMo+jvcU+HLZaFY/Lh7TZ29Q5kE2ZIk+N6JpcYmWyf/9FVyWW59pf5zRNlnfc5KClhUn7vfAmHNObpham24+BTO+06fONhUn70cGmrPGbXyzMZryz4Mdfwsx752Sk/Zz5RKnMzBTcRidVHzCPozLZV/ATdW9T/b3HnY84c/BMpupxY+YHrQ5uvx38DmZnZIq+dvJsrM/bpmf+B/V0baIl/+n+AAAAAElFTkSuQmCC"];

我的回复是:

requestReply: {"Message":"An error has occurred.","ExceptionMessage":"Parameter is not valid.","ExceptionType":"System.ArgumentException","StackTrace":"
at System.Drawing.Image.FromStream(Stream stream, Boolean useEmbeddedColorManagement, Boolean validateImageData)
at System.Drawing.Image.FromStream(Stream stream, Boolean useEmbeddedColorManagement)
at RKB.RestAPI.V1Controller.insertimages(getimage _get) in d:\\Projects\\RKB_RestAPI\\V1.cs:line 568
at lambda_method(Closure , Object , Object[] )
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass13.<GetExecutor>b__c(Object instance, Object[] methodParameters)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.<>c__DisplayClass5.<ExecuteAsync>b__4()
at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)"}

但如果我使用 ANDROID 运行此API,我会得到正确的回复

ANDROID代码是:

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
Log.d(TAG, "ba1: "+ba1);


  nameValuePairs.add(new BasicNameValuePair("user_id", "121");
  nameValuePairs.add(new BasicNameValuePair("imageget", "same as my image data");



try{
    HttpClient httpclient = new DefaultHttpClient();

    HttpPost httppost = new HttpPost("http://taxi.expertverification.com/api/v1/Getimage";

    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();               

    String outPut = EntityUtils.toString(entity);
    Log.i("GET RESPONSE—-", outPut);

    Log.e("log_tag ******", "good connection";

    bitmapOrg.recycle();
}catch (Exception e) {
    Log.e("log_tag ******", "Error in http connection " + e.toString());
}

代码(用于ANDROID)与我上午发布的相同。

如果你不介意,请你帮我解决这个问题

2 个答案:

答案 0 :(得分:1)

您遇到的问题是,您需要在汇总表单数据之前对base64数据进行URL编码(它填充+ s解码到空格,而不是+ s)

可能的选择:

  • 使用CFURLCreateStringByAddingPercentEscapes(确保在要转义的字符中包含+)或stringByAddingPercentEncodingWithAllowedCharacters:以转义数据(在汇总之前)
  • 使用一些可以为您执行此操作的现有库
  • 切换到更易于操作的其他格式,例如JSON

这是我个人用于网址转义数据的类别:

<强>的NSString + urlencode.h

#import <Foundation/Foundation.h>

@interface NSString (urlencode)

- (NSString *)escapedValueForURLParameter;

@end

<强>的NSString + urlencode.m

#import "NSString+urlencode.h"

@implementation NSString (urlencode)

- (NSString *)escapedValueForURLParameter
{
    return (__bridge_transfer NSString *)
        CFURLCreateStringByAddingPercentEscapes(
                                                NULL,
                                                (__bridge CFStringRef) self,
                                                NULL,
                                                (CFStringRef) @"!*'();:@&=+$,/?%#[]",
                                                kCFStringEncodingUTF8
                                            );
}

@end

答案 1 :(得分:-1)

我认为使用AFNetworking

很容易解决这个问题

它将大大简化您的流程,为您节省大量时间。它是开发人员广泛使用的框架。

https://github.com/AFNetworking/AFNetworking

您可以使用几行(POST-multipart request)轻松发送带参数的图像:

例如检查此代码。(确保参考上面的链接并添加相应的头文件)

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"foo": @"bar"};
NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
[manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFileURL:filePath name:@"image" error:nil];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Success: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];