【问题标题】:IOS HttpPost with parametersIOS HttpPost 带参数
【发布时间】:2013-04-21 11:39:27
【问题描述】:

我想发送带有参数的 http post,然后从响应中检索 cookie。

在 android 中我使用以下内容:

HttpPost request = new HttpPost("http://stackoverflow.com/");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); 
nameValuePairs.add(new BasicNameValuePair("parameter", parameter));  
request.setEntity(new UrlEncodedFormEntity(nameValuePairs));  

HttpResponse response = client.execute(request);

List<Cookie> cookies = client.getCookieStore().getCookies();

我尝试在 IOS 中使用以下内容,但对我不起作用:

NSURL *authUrl = [[NSURL alloc] initWithString:@"http://stackoverflow.com/"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:authUrl];
[request setHTTPMethod:@"POST"];
NSString * parameters = [NSString stringWithFormat:@"login=%@&password=%@",login,password];
NSData *requestData = [NSData dataWithBytes:[parameters UTF8String] length:[parameters length]];
[request setHTTPBody:requestData];
[request setTimeoutInterval:15.0];
NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];

在委托方法中,我接收数据。但是数据看起来像是在没有参数的情况下发送了帖子。我猜它发送链接但不发送参数。我还尝试设置标题,但对我没有帮助。

[request addValue:VALUE forHTTPHeaderField:@"login"]; 

并且使用sendSynchronousRequest 也没有帮助。

NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

我做错了什么?

【问题讨论】:

  • 根据登录名和密码参数,此行将无法正常工作:'NSData *requestData = [NSData dataWithBytes:[parameters UTF8String] length:[parameters length]];'因为计算的长度可能是错误的。您从服务器收到的错误是验证错误吗?
  • 一切正常(长度正确)。服务器没有验证错误。但它没有正确发送参数。我收到的网页内容与我发送的不带参数的 url 相同。
  • 您如何证明一切正常?您是否验证了实际发送的请求数据(使用代理检测)或检查了服务器接收到的数据?
  • 我终于完成了。问题出在 authUrl 上。我错过了网址末尾的“/”。这就是为什么服务器收到正确的参数但没有对它们做任何事情。所以如果有人需要,这段代码就可以工作。

标签: ios cookies http-post httpclient


【解决方案1】:

源工作正常,但我向错误的网站发送请求。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多