使用参数的Http Post请求

3

我有一个简单的asp.net Web服务,它返回json格式的数据。我想发送带参数的http post请求来获取json数据。我该如何发送请求并获取数据?

post请求:

POST /JsonWS.asmx/FirmaGetir HTTP/1.1
Host: localhost
Content-Type: application/x-www-form-urlencoded
Content-Length: length

firID=string

answer:

HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length    
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">string</string>

我尝试了一些代码,但它们没有起作用。

NSString *firmadi =@"";
NSMutableData *response;


-(IBAction)buttonClick:(id)sender
{
    NSString *firid = [NSString stringWithFormat:@"800"];

    response = [[NSMutableData data] retain];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://192.168.1.23/testService/JsonWS.asmx?op=FirmaGetir"]];

    NSString *params = [[NSString alloc] initWithFormat:@"firID=%@",firid];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [[NSURLConnection alloc] initWithRequest:request delegate:self];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    if(theConnection)
    {
        response = [[NSMutableData data] retain];

    }
    else 
    {
        NSLog(@"theConnection is null");
    }

}

-(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)responsed
{
    [response setLength:0];
     NSURLResponse * httpResponse;

    httpResponse = (NSURLResponse *) responsed;

}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
{
    [response appendData:data];
    //NSLog(@"webdata: %@", data);

}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError*)error
{
    NSLog(@"error with the connection");
    [connection release];
    [response release];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{

    response = [[NSMutableData data] retain];

 NSString *responseString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
    NSLog(@"%@",responseString);

}

1
你尝试过将请求的 MIME 类型设置为 'application/json' 而不是 'application/x-www-form-urlencoded' 吗? - George Green
这是来自我的网络服务,为什么我要更改这个设置? - Melih Mucuk
你发布的代码有什么问题? - George Green
屏幕上有一个按钮。当我按下按钮时,我想看到我的服务结果。但是没有发生。 - Melih Mucuk
在didFinishLoading中,response = [[NSMutableData data] retain]]会导致你在使用它之前丢失所有已下载的数据,将其放在NSString *responseString之后。 - George Green
2个回答

1
你在这里做什么:
[[NSURLConnection alloc] initWithRequest:request delegate:self];

这行代码返回了一个 NSURLConnection,但你没有存储它。这对你没有任何作用。
在读取数据之前,你清除了数据:
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    response = [[NSMutableData data] retain]; // This line is clearing your data get rid of it
    NSString *responseString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
    NSLog(@"%@",responseString);

}

编辑

-(IBAction)buttonClick:(id)sender {

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://192.168.1.23/testService/JsonWS.asmx?op=FirmaGetir"]
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                                                       timeoutInterval:15];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:[@"firID=800" dataUsingEncoding:NSUTF8StringEncoding]];
    self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [self.connection start];

}


#pragma NSURLConnection Delegates

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    if (!self.receivedData){
        self.receivedData = [NSMutableData data];
    }
    [self.receivedData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

     NSString *responseString = [[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding];
     NSLog(@"%@",responseString);
}

感谢关注。我是iOS开发的新手,因此我的代码中有一些愚蠢的代码块。我之所以提问,就是为了解决这个问题。我会尝试这些方法,但请您写出完整的代码过程。 - Melih Mucuk
我找到了不同的解决方案,但是我感谢你的回答。 - Melih Mucuk
这是 NSURLConnection sendAsynchronousRequest:queue:completionHandler: 吗?有几种不同的解决方案。我发布的那个基于你发布的内容。它非常适用于身份验证和自定义。sendAsynchronousRequest:queue:completionHandler: 对于简单的异步调用非常好。 - Jaybit
您不需要调用theConnection的start方法。它会立即开始除非您使用了 - (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately 且将startImmediately设为NO。 - malex

0

今天早上我遇到了这个问题,现在才解决。我猜你的问题关键在于如何使用带参数的POST方法。实际上,它非常简单。

(1) 首先,您应该确保您要发送的文件已经准备好了。这里我们用一个NSString变量叫stringReady作为我们postRequest方法的参数(这不是我们想要讨论的HTTP POST参数,不用担心)。

// Send JSON to server
- (void) postRequest:(NSString *)stringReady{
// Create a new NSMutableURLRequest
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.xxxxxx.io/addcpd.php"]];
[req setHTTPMethod:@"POST"];

(2) 现在,我们说服务器想要获取的参数称为“data”,这是将参数插入HTTP正文的方法。

// Add the [data] parameter
NSString *bodyWithPara = [NSString stringWithFormat:@"data=%@",stringReady];

看,这是在使用POST方法时添加参数的方式。你只需要在要发送的文件之前简单地放置参数即可。如果你已经知道你的参数,那么最好查看一下这个网站:

https://www.hurl.it/

这将帮助您测试是否正确发送文件,并在网站底部显示响应。

(3) 第三步,我们将NSString打包成NSData并发送到服务器。

// Convert the String to NSData
NSData *postData = [bodyWithPara dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
// Set the content length and http body
NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];
[req addValue:postLength forHTTPHeaderField:@"Content-Length"];
[req setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[req setHTTPBody:postData];
// Create an NSURLSession
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:req
                                        completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                            // Do something with response data here - convert to JSON, check if error exists, etc....
                                            if (!data) {
                                                NSLog(@"No data returned from the sever, error occured: %@", error);
                                                return;
                                            }

                                            NSLog(@"got the NSData fine. here it is...\n%@\n", data);
                                            NSLog(@"next step, deserialising");

                                            NSError *deserr;
                                            NSDictionary *responseDict = [NSJSONSerialization
                                                                          JSONObjectWithData:data
                                                                          options:kNilOptions
                                                                          error:&deserr];
                                            NSLog(@"so, here's the responseDict\n\n\n%@\n\n\n", responseDict);
                                        }];

[task resume];}

希望这能帮助到在这里卡住的人。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接