3

json形式のデータを返す単純なasp.netWebサービスがあります。jsonデータを取得するためのパラメーターを指定してhttppostリクエストを送信したいと思います。リクエストを送信してデータを取得するにはどうすればよいですか?

ポストリクエスト:

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

firID=string

答え:

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);

}
4

2 に答える 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);
}
于 2013-02-13T17:00:26.047 に答える
0

私は今朝この問題に苦しみました、そして私は今それを理解しています。あなたの質問の鍵は、パラメータでPOSTメソッドを使用する方法だと思います。実際、それは非常に簡単です。

(1)まず、ファイルを送信する準備ができていることを確認する必要があります。ここでは、stringReadyと呼ばれるNSStringであると言います。これを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)ここで、サーバーが取得したいパラメーターを「データ」と呼びます。これは、パラメーターをHTTPボディに挿入する方法です。

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

ほら、POSTメソッドを使用するときにパラメータを追加する方法です。送信したいファイルの前にパラメータを置くだけです。あなたがあなたのパラメータが何であるかを知っているなら、あなたはこのウェブサイトをチェックする方が良いかもしれません:

https://www.hurl.it/

これは、ファイルを適切に送信しているかどうかをテストするのに役立ち、Webサイトの下部に応答が表示されます。

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

これがここで立ち往生している誰かを助けることができることを願っています。

于 2017-08-03T03:02:50.700 に答える