我遇到http Post request
问题,情况如下:
我必须发送带文字的帖子请求,并在此处输入代码:
NSMutableURLRequest *eventRequest = [NSMutableURLRequest requestWithURL:_urlRequest cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:500];
NSString *boundary = @"---------------------------14737809831466499882746641449";
//Set header Http POST
[eventRequest setHTTPMethod:@"POST"];
[eventRequest setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]forHTTPHeaderField:@"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"parameter1\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[self postParametre] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//Image upload
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: immage/jpg \r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Disposition: form-data; filename=\"immagine.jpg\""dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:data];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// Close boundary
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// set request body
[eventRequest setHTTPBody:body];
NSString* string = [[NSString alloc] initWithData:body encoding:NSUTF8StringEncoding];
NSLog(@"Stampa Dati inviati: %@", string);
// Http header Content-Lenght
[eventRequest setValue:[NSString stringWithFormat:@"%i",[data length]] forHTTPHeaderField:@"Content-Length"];
self.theConnection=[[NSURLConnection alloc] initWithRequest:eventRequest delegate:self];
if (self.theConnection) {
self.receivedData = [[NSMutableData data] retain];
} else {
// Inform the user that the connection failed.
NSLog(@"Connection Problem");
}
可以看到我设置i为身体的第一部分设置了"Content-Type"
的多部分/表格数据我设置了文本,而在第二部分设置了图像,但是图像是正确上传但没有“扩展”,并在第一个我设置要发送的文本,但文本显然没有设置或格式没有被读取到服务器。
方法[self postParametre]
返回NSMutableString
格式为“key1 = value1& key2 = value2& key3 = value3”。
任何人都可以帮助我吗?
问候。
答案 0 :(得分:0)
您可以使用https://github.com/AFNetworking/AFNetworking。
AFHTTPClient有一个方法multipartFormRequestWithMethod。这将以多部分上传图像。