Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dolphinSuPixnet/421ba46cebb0f44410b2 to your computer and use it in GitHub Desktop.
Save dolphinSuPixnet/421ba46cebb0f44410b2 to your computer and use it in GitHub Desktop.
這樣可以產生一個 http method 為 POST,http body 為 multipart/form-data 的 url request
+(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