我有问题。我正在向服务器发出POST请求。我用user_id上传一个用户的图像。我需要发送x-www-form-urlencoded中的user_id和from-data中的Image。我尝试了很多方法,但每次在服务器中未定义user_id时。如何在同一请求中发送两者。 这是我的 CODE:
NSString *urlString = [[NSString alloc]initWithString:[NSString stringWithFormat:@"MY URL TO UPLOAD IMAGE "]];
urlString=[urlString stringByAddingPercentEscapesUsingEncoding:
NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:100];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"------V2ymHFg03ehbqgZCaKO6jy";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];
[request addValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
NSDictionary *params = @{@"user_id":@"213"};
NSMutableData *body = [NSMutableData data];
for (NSString *param in params) {
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: x-www-form-urlencoded; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"%@\r\n", [params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}
// add image data
NSData *imageData = UIImageJPEGRepresentation(image, .3);
if (imageData) {
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"my-file\"; filename=\"%@.jpg\"\r\n",@"213"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: image/jpg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
NSURLResponse *urlResponse;
NSError *error;
NSData * data=[NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
输出:数据= nil
答案 0 :(得分:0)
要通过POST
[request setHTTPMethod:@"POST"];
NSString *myString = [NSString stringWithFormat:@"value1=test3&value2=test"];
[request setHTTPBody:[myString dataUsingEncoding:NSUTF8StringEncoding]];