Add HTTP Header to NSURLRequest

前端 未结 3 926
星月不相逢
星月不相逢 2020-12-02 12:11

Is there any way to add HTTP header to NSURLRequest object? I used to add them in NSMutableURLRequest using:

[request addValue:@\"P         


        
3条回答
  •  心在旅途
    2020-12-02 12:57

    NSString *urlString = @"http://10.28.79.63:3000/testing";
    
    NSMutableURLRequest *imageRequest = [[NSMutableURLRequest alloc] init] ;
    [imageRequest setURL:[NSURL URLWithString:urlString]];
    [imageRequest setHTTPMethod:@"POST"];
    
    NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    
    [imageRequest setValue:contentType forHTTPHeaderField: @"content-Type"]; 
    NSMutableData *body = [NSMutableData dataWithCapacity:[imageData length] + 512];
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n",boundary]dataUsingEncoding:NSUTF8StringEncoding]]; 
    
    //Here u adds the Headers which will be posted in body 
    
    [body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; content-type: application/octet-stream; name=\"userfile\"; filename=\"inLove.mp4\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    
    
    [body appendData:[NSData dataWithData:imageData]];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
    [imageRequest setHTTPBody:body];
    NSURLConnection * theConnection = [[NSURLConnection alloc] initWithRequest:imageRequest 
                                                    delegate:self];
    

提交回复
热议问题