Created
November 4, 2015 07:33
-
-
Save dolphinSuPixnet/421ba46cebb0f44410b2 to your computer and use it in GitHub Desktop.
這樣可以產生一個 http method 為 POST,http body 為 multipart/form-data 的 url request
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
+(instancetype)PIXURLRequestForOauth2POST:(NSString *)urlString parameters:(NSDictionary *)parameters{ | |
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]]; | |
request.HTTPMethod = @"POST"; | |
//設定 http header | |
NSString *contentTypeValue = [NSString stringWithFormat:@"multipart/form-data; charset=utf-8; boundary=%@", kBoundaryConstant]; | |
[request addValue:contentTypeValue forHTTPHeaderField:@"Content-Type"]; | |
//設定 http body | |
[request setHTTPBody:[stringForFormData(parameters) dataUsingEncoding:NSUTF8StringEncoding]]; | |
return request; | |
} | |
static NSString* stringForFormData(NSDictionary *parameters){ | |
// 做為 form data 參數間的分隔線,前面要有兩個減號 | |
NSString *boundaryWtihNewLine = [NSString stringWithFormat:@"--%@%@", kBoundaryConstant, kNewLineSymbol]; | |
__block NSMutableArray *array = [NSMutableArray array]; | |
[parameters enumerateKeysAndObjectsUsingBlock:^(NSString *_Nonnull key, NSString *_Nonnull obj, BOOL * _Nonnull stop) { | |
NSString *string = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"%@%@%@%@", key, kNewLineSymbol, kNewLineSymbol, obj, kNewLineSymbol];; | |
[array addObject:string]; | |
}]; | |
NSString *string = [array componentsJoinedByString:boundaryWtihNewLine]; | |
// 做為 form data 所有參數的結尾的 boundary,前後都要有兩個減號 | |
string = [NSString stringWithFormat:@"%@%@--%@--", boundaryWtihNewLine, string, kBoundaryConstant]; | |
return string; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment