天天看點

使用NSMutableURLRequest和NSURLConnection 以Post方式上傳照片

接下來我想用系統的NSURLConnection來實作這個功能:

首先我們要定義一個全局變量:

@property (nonatomic, strong) NSMutableData *mResponseData;

實作代碼:

//字典裡面裝的是你要上傳的内容

NSDictionary *parameters = @{@"content": @"這是剛剛線上的官方網站www.baidu.com"};

//上傳的接口

NSString* urlstring = @"http://superqq.com/";

//分界線的辨別符

NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";

//根據url初始化request

NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlstring]

                                                        cachePolicy:NSURLRequestReloadIgnoringLocalCacheData

                                                    timeoutInterval:10];

//分界線 --AaB03x

NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];

//結束符 AaB03x--

NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];

//    //要上傳的圖檔

//    UIImage *image=[params objectForKey:@"pic"];

//得到圖檔的data

NSData *data = UIImagePNGRepresentation(self.image);

//http body的字元串

NSMutableString *body=[[NSMutableString alloc]init];

//參數的集合的所有key的集合

NSArray *keys= [parameters allKeys];

//周遊keys

for(int i=0;i<[keys count];i++)

{

    //得到目前key

    NSString *key=[keys objectAtIndex:i];

    //如果key不是pic,說明value是字元類型,比如name:Boris

    if(![key isEqualToString:@"pic"])

    {

        //添加分界線,換行

        [body appendFormat:@"%@\r\n",MPboundary];

        //添加字段名稱,換2行

        [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];

        //添加字段的值

        [body appendFormat:@"%@\r\n",[parameters objectForKey:key]];

    }

}

添加分界線,換行

[body appendFormat:@"%@\r\n",MPboundary];

//聲明pic字段,檔案名為boris.png

[body appendFormat:@"Content-Disposition: form-data; name=\"pic\"; filename=\"boris.png\"\r\n"];

//聲明上傳檔案的格式

[body appendFormat:@"Content-Type: image/png\r\n\r\n"];

//聲明結束符:--AaB03x--

NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];

//聲明myRequestData,用來放入http body

NSMutableData *myRequestData=[NSMutableData data];

//将body字元串轉化為UTF8格式的二進制

[myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];

//将image的data加入

[myRequestData appendData:data];

//加入結束符--AaB03x--

[myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];

//設定HTTPHeader中Content-Type的值

NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];

//設定HTTPHeader

[request setValue:content forHTTPHeaderField:@"Content-Type"];

//設定Content-Length

[request setValue:[NSString stringWithFormat:@"%d", (int)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];

//設定http body

[request setHTTPBody:myRequestData];

//http method

[request setHTTPMethod:@"POST"];

//建立連接配接,設定代理

NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

//設定接受response的data

if (conn) {

    _mResponseData = [[NSMutableData alloc] init];

}

NSURLConnectionDelegate的代理方法:

#pragma mark - NSURLConnectionDelegate

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{

   [_mResponseData setLength:0];

}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

   [_mResponseData appendData:data];

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

   NSDictionary *dic =  [NSJSONSerialization JSONObjectWithData:_mResponseData options:kNilOptions error:nil];

   NSLog(@"%@", dic);

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

{

   NSLog(@"Error: %@", error);

}

繼續閱讀