Http Post Request [英] Http Post Request

查看:88
本文介绍了Http Post Request的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to make Http Post Request using JSON. I tried every option which is available on Internet.But could not get the Data. So please post entire code to make a request.

推荐答案

您可以使用以下代码:


-(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]; 
    }
}

这篇关于Http Post Request的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆