我有这个json:
{“myFriends”:{“userId”:“用户ID”,“userName”:“用户名”,“朋友”:[{“u”:“朋友用户ID”,“n”:“朋友用户名“},{”u“:”朋友用户ID“,”n“:”朋友用户名“}]}}
我希望将他的帖子请求发送给服务器,这是我尝试这样做的当前方式:
+(NSData *)postDataToUrl:(NSString*)urlString :(NSString*)jsonString
{
NSData* responseData = nil;
NSURL *url=[NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
responseData = [NSMutableData data] ;
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
NSString *bodydata=[NSString stringWithFormat:@"%@",jsonString];
[request setHTTPMethod:@"POST"];
NSData *req=[NSData dataWithBytes:[bodydata UTF8String] length:[bodydata length]];
[request setHTTPBody:req];
NSURLResponse* response;
NSError* error = nil;
responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"the final output is:%@",responseString);
return responseData;
}
json字符串包含json,但由于某种原因,服务器总是得到nil并返回错误。如何解决这个问题?
答案 0 :(得分:1)
告诉您的服务器有关内容类型肯定会有所帮助:
[request addValue:@"application/json"
forHTTPHeaderField:@"Content-Type"];
此外:在我自己的代码中,我使用:
[request setHTTPBody:[bodydata dataUsingEncoding:NSUTF8StringEncoding]]
答案 1 :(得分:0)
这是我的带有NSData参数的POST请求代码:
- (void)uploadJSONData:(NSData*)jsonData toPath:(NSString*)urlString {
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:kRequestTimeout];
[request setHTTPMethod:@"POST"];
[request setHTTPBody: data];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[data length]] forHTTPHeaderField:@"Content-Length"];
// Create url connection and fire request
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[connection scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
[connection start];
}
这是针对异步请求的,但它应该适用于同步。我唯一看到你可能遗失的是" Content-Length"参数。