Http Post Request

时间:2010-10-19 12:06:19

标签: iphone json http

如何使用JSON制作Http Post Request。我尝试了Internet上可用的每个选项。但无法获取数据。所以请发布完整的代码来提出请求。

2 个答案:

答案 0 :(得分:4)

您可以使用以下代码:


-(void)performRequest{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"url"]];
    NSString *msgLength = [NSString stringWithFormat:@"%d", [jsonMessage length]];
    [request addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request addValue: jsonAction forHTTPHeaderField:@"JSONAction"];
    [request addValue: msgLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody: [jsonMessage dataUsingEncoding:NSUTF8StringEncoding]];
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if( theConnection )
    {
        webData = [[NSMutableData data] retain];
    }
    else
    {
        NSLog(@"theConnection is NULL");
    }
    [pool release];
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    [webData setLength: 0];
    self.resultArray = [[NSMutableArray alloc] init];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"ERROR with theConenction");
    NSDictionary *errorDic = [NSDictionary dictionaryWithObject:error forKey:@"error"];
    [self.resultArray addObject:errorDic];
    [connection release];
    [webData setLength:0];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSLog(@"DONE. Received Bytes: %d", [webData length]);
    NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
    NSLog(@"%@", theXML);
    [theXML release];
    if([webData length] > 0){
        parser = [[NSXMLParser alloc] initWithData:webData];
        [parser setDelegate:self];
        [parser parse]; 
    }
}

答案 1 :(得分:3)

以下是NSURLConnection将JSON发布到URL的基本示例。

- (void)performRequest {
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://someplace.com/"]];
    [request setValue:@"Some Value" forHTTPHeaderField:@"Some-Header"];
    [request setHTTPBody:@"{\"add_json\":\"here\"}"];
    [request setHTTPMethod:@"POST"];
    [NSURLConnection connectionWithRequest:[request autorelease] delegate:self];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
     // Fail..
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
     // Request performed.
}