object-c NSMutableURLRequest模拟表单提交

NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];

 
 
    [urlRequest setHTTPMethod:@"POST"];
 
    [urlRequest setValue: [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BOUNDRY]
 
      forHTTPHeaderField:@"Content-Type"];
 
 
 
 
int len=512;
 
if(imageData !=nil){
 
len = imageData.length + 512;
 
}
 
NSMutableData  * postData =[NSMutableData dataWithCapacity:len];
 
 
[postData  appendData: [[NSString  stringWithFormat:@"--%@\r\n",BOUNDRY] dataUsingEncoding:NSUTF8StringEncoding]];
 
[postData  appendData: [[NSString  stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",@"token" ] dataUsingEncoding:NSUTF8StringEncoding]];
 
[postData  appendData: [[NSString  stringWithFormat:@"%@",user.token] dataUsingEncoding:NSUTF8StringEncoding]];
 
[postData  appendData: [[NSString  stringWithFormat:@"\r\n--%@\r\n",BOUNDRY] dataUsingEncoding:NSUTF8StringEncoding]];
 
 
 
[postData  appendData: [[NSString  stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",@"timestamp" ] dataUsingEncoding:NSUTF8StringEncoding]];
 
[postData  appendData:[[NSString   stringWithFormat:@"%@",timestamp] dataUsingEncoding:NSUTF8StringEncoding]];
 
[postData  appendData:[[NSString   stringWithFormat:@"\r\n--%@\r\n",BOUNDRY] dataUsingEncoding:NSUTF8StringEncoding]];
 
 
[postData  appendData: [[NSString  stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",@"signature" ] dataUsingEncoding:NSUTF8StringEncoding]];
 
[postData  appendData:[[NSString   stringWithFormat:@"%@",signature] dataUsingEncoding:NSUTF8StringEncoding]];
 
 
 
if (imageData != nil ) {
 
[postData  appendData:[[NSString   stringWithFormat:@"\r\n--%@\r\n",BOUNDRY] dataUsingEncoding:NSUTF8StringEncoding]];
 
[postData  appendData: [[NSString  stringWithFormat:@"Content-Disposition: form-data; name=\"%@\";filename=\"temp.png\"\r\nContent-Type: image/png\r\n\r\n",@"upfile" ] dataUsingEncoding:NSUTF8StringEncoding]];
 
[postData  appendData:imageData];
 
}   
 
 
[postData  appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",BOUNDRY] dataUsingEncoding:NSUTF8StringEncoding]];
 
 
    [urlRequest setHTTPBody:postData];
    NSLog(@"%@",urlRequest); 
 
 
 
NSData *returnData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil];  
 
 
 
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];  
NSLog(@"%@",returnString);  
 

你可能感兴趣的:(request)