Ios 将数据追加到POST请求

Ios 将数据追加到POST请求,ios,objective-c,nsurlrequest,Ios,Objective C,Nsurlrequest,如何将数据附加到现有的POSTNSURLRequest?我需要添加一个新参数userId=2323如果您不希望使用第三方类,那么下面是如何设置帖子正文的 NSURL *url= [NSURL URLWithString:@"https://www.paypal.com/cgi-bin/webscr"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl

如何将数据附加到现有的
POST
NSURLRequest
?我需要添加一个新参数
userId=2323

如果您不希望使用第三方类,那么下面是如何设置帖子正文的

 NSURL *url= [NSURL URLWithString:@"https://www.paypal.com/cgi-bin/webscr"];
 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
                                                        cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                    timeoutInterval:10.0];
[request setHTTPMethod:@"POST"];
 NSString *postString = @"userId=2323";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
NSURL *aUrl = [NSURL URLWithString:@"http://www.apple.com/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
                                         cachePolicy:NSURLRequestUseProtocolCachePolicy
                                     timeoutInterval:60.0];

[request setHTTPMethod:@"POST"];
NSString *postString = @"company=Locassa&quality=AWESOME!";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request 
                                                             delegate:self];

只需将您的键/值对附加到post字符串

上面的示例代码对我很有帮助,但是(如上所述),我认为您需要使用
NSMutableURLRequest
而不是
NSURLRequest
。在它当前的形式中,我无法让它响应
setHTTPMethod
调用。更改类型可以立即解决问题。

在调用
NSURLConnection
之前,必须对
NSMutableURLRequest
进行所有更改

当我复制并粘贴上面的代码并运行
TCPMon
时,我看到了这个问题,并且看到请求是
GET
,而不是预期的
POST

NSURL *aUrl = [NSURL URLWithString:@"http://www.apple.com/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
                                     cachePolicy:NSURLRequestUseProtocolCachePolicy
                                 timeoutInterval:60.0];


[request setHTTPMethod:@"POST"];
NSString *postString = @"company=Locassa&quality=AWESOME!";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request 
                                                         delegate:self];

前面关于生成
POST
请求的帖子基本上是正确的(将参数添加到正文,而不是URL)。但若输入数据可能包含任何保留字符(如空格、符号和加号),则您将需要处理这些保留字符。也就是说,您应该转义输入

//create body of the request

NSString *userid = ...
NSString *encodedUserid = [self percentEscapeString:userid];
NSString *postString    = [NSString stringWithFormat:@"userid=%@", encodedUserid];
NSData   *postBody      = [postString dataUsingEncoding:NSUTF8StringEncoding];

//initialize a request from url

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPBody:postBody];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

//initialize a connection from request, any way you want to, e.g.

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
其中,
precentEscapeString
方法定义如下:

- (NSString *)percentEscapeString:(NSString *)string
{
    NSString *result = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                                 (CFStringRef)string,
                                                                                 (CFStringRef)@" ",
                                                                                 (CFStringRef)@":/?@!$&'()*+,;=",
                                                                                 kCFStringEncodingUTF8));
    return [result stringByReplacingOccurrencesOfString:@" " withString:@"+"];
}
注意,有一种很有前途的
NSString
方法,
stringByAddingPercentEscapesUsingEncoding
(现在已弃用),它做了一些非常类似的事情,但不想使用它。它处理一些字符(例如空格字符),但不处理其他字符(例如
+
&
字符)

当代的等价物是
stringByAddingPercentEncodingWithAllowedCharacters
,但是,同样,不要尝试使用
URLQueryAllowedCharacterSet
,因为这也允许
+
&
传递未替换。这两个字符允许出现在更广泛的“查询”中,但如果这些字符出现在查询中的某个值中,则它们必须转义。从技术上讲,您可以使用
URLQueryAllowedCharacterSet
构建可变角色集并删除其中包含的一些角色,也可以从头构建自己的角色集


例如,如果您查看Alamofire的,它们会采用
URLQueryAllowedCharacterSet
,然后删除
GeneralDelimiterToEncode
(其中包括字符
#
[
]
,以及
@
,但由于一些旧web服务器中存在历史性缺陷,因此
)和
子定界符toencode
(即
$
*
+
,和
=/code>)。这是正确的实现(尽管您可能会对删除
/
进行辩论),尽管这相当复杂。也许
CFURLCreateStringByAddingPercentEscapes
更直接/有效

任何寻求快速解决方案的人

let url = NSURL(string: "http://www.apple.com/")
let request = NSMutableURLRequest(URL: url!)
request.HTTPBody = "company=Locassa&quality=AWESOME!".dataUsingEncoding(NSUTF8StringEncoding)

请用一些代码描述您的问题。我需要将新参数添加到现有NSURLRequest,而不是创建新请求。我认为必须首先将其转换为NSMutableURLRequest。我不知道的是如何获取现有POST数据。换句话说,如何获取现有请求的postString?您可以访问-(NSData*)HTTPBody,您可以将其编码为NSString、键/值对现有POST数据以UTF8编码,如您的示例所示。如何反转编码?然后用新参数创建一个新字符串?然后对新的post数据进行编码这应该可以工作,但我目前无法测试它。。。。NSMutableString*existingPost=[[NSMutableString alloc]initWithData:[req HTTPBody]编码:NSUTF8StringEncoding];[existingPost appendFormat:@“&%@=%@”、@“name”、@“Locassa”];关于
stringByAddingPercentEscapesUsingEncoding:
,则为True,但
stringByAddingPercentEncodingWithAllowedCharacters:
适用于每个字符。示例:
URLString=[URLString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet-URLQueryAllowedCharacterSet]]
@Alejandrodavidcodotrarojas-您可以通过添加允许字符的百分比编码来使用
字符串,但不能使用
URLQueryAllowedCharacterSet
,因为这包括
+
&
(这些是更广泛查询中允许的字符,但如果这些字符出现在查询中的值中,则必须转义,而该字符集不会这样做)。因此,您可以使用
URLQueryAllowedCharacterSet
构建可变字符集并删除其中包含的一些字符,或者从头开始构建您自己的字符集。或者使用
cfurlCreateStringByAddingPercentesEscapes
。很好的回答,确实可以使用Alamofire避免所有这些depth!鉴于
CFURLCreateStringByAddingPercentEscapes
现在已被弃用,您确实应该自己构建相应的字符集。请参阅。