簡體   English   中英

如何將URL參數添加到JSON Web服務調用-目標C

[英]How to add URL parameters to JSON web service call - Objective C

我正在嘗試使用SBJsonParser API使用以下代碼從JSON Web服務中獲取信息:

 SBJsonParser *parser = [[SBJsonParser alloc] init];

// Prepare URL request to download statuses from Twitter
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://twitter.com/statuses/public_timeline.json"]];

// Perform request and get JSON back as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];

但是我需要在Web服務URL中添加兩個參數(用戶和密碼)及其值,因此URL將為“ http://twitter.com/statuses/public_timeline.json?user=name&password=test”。 我已經搜索了有關API的信息,但是沒有成功。

非常感謝您的幫助。

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://twitter.com/statuses/public_timeline.json?user=%@&password=%@", @"name", @"test"]]];

根據需要用自己的變量替換@"name"@"test"

我假設您有變量中的值,對嗎? 如果是這樣,只需使用NSString的stringWithFormat:方法。

更換:

@"http://twitter.com/statuses/public_timeline.json"

帶有:

[NSString stringWithFormat:@"http://twitter.com/statuses/public_timeline.json?user=%@&password=%@", user, password]
NSString *user = @"user";
NSString *password = @"password";

NSString *urlStr = [NSString stringWithFormat:@"http://twitter.com/statuses/public_timeline.json?user=%@&password=%@", user, password];

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: urlStr]];

您也可以這樣做。

 NSMutableURLRequest *theRequest = [[NSMutableURLRequest alloc] initWithURL:@"http://twitter.com/statuses/public_timeline.json"];

 [theRequest setHTTPMethod:"@POST"] // Or get, push, put

 NSString theRquest_Body = [NSString stringWithFormat:@"?user=%@&password=%@",
                           [user stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
                           [password stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]],

 [theRequest setHTTPBody:[theRequest_body dataUsingEncoding:NSUTF8StringEncoding]];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM