首先,我已经查找了如何发出发布请求,并阅读了有关如何创建一个帖子的多个线程和文档,但是我的数据似乎不起作用。我有两个字段说 x 和 html,我想对调用调用名进行。这种 GET 形式将是 www.someserver.com/callname?x=something&y=something到目前为止,我的 POST 代码如下所示:
NSString *baseURLString = @"http://www.someserver.com/callname"
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[[NSURL URLWithString:baseURLString] standardizedURL]];
NSString *fields = [NSString stringWIthFormat:@"x=%@&html=%@",x,htmlSource];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:[NSData dataWithBytes:[fields UTF8String] length:strlen([fields UTF8String])]];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
以这种方式实现的 NSURLConnection 委托方法
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
NSLog(@"Data Received");
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"Error: %@" , error);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(@"Connection Finished");
}
我错过了什么吗?除了编码的选择之外,我的代码看起来与我找到的大多数示例非常相似。我将 html 源代码作为 y 的值传递重要吗?任何提示或提示将不胜感激。我对iOS和html处理一般都很陌生,所以请原谅我对这个主题缺乏了解。谢谢你的时间!
您必须实现委托协议,NSURLConnection
才能获得响应。您尚未发布任何该代码,因此我认为这意味着您没有实现相关方法。
一个潜在的问题是您错过了对参数进行正确百分比编码:
当在代码中使用带有内容类型application/x-www-form-urlencoded
的参数时,我建议将参数创建为(未编码的)键/值对NSString
,创建一个NSDictionary
对象并使用以下帮助程序方法在此处的答案中描述(如何在 HTTP 帖子中将多个参数发送到 PHP 服务器),该方法创建一个正确编码的参数字符串,您可以将其添加到正文中。
您的表单 URL 编码不正确。我相信解决方案如下
[serviceRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
如果你想对你的值进行 UTF-8 编码,你需要先做,例如,
NSString *postLength = [NSString stringWithFormat:@"%d", [_xmlDoc length]]; //Calculating the Content Length
NSData *postData = [_xmlDoc dataUsingEncoding:NSUTF8StringEncoding]; // preparing XML to be sent in POST
请注意,您提前对 POST 数据的字符串进行了编码。
希望这有帮助!!
class Requests {
class func loginRequest(userName:String, password:String, completion: @escaping ((JSON?, String?) -> ()) )
{
var request = URLRequest(url: URL(string: "your URL")!)
request.httpMethod = "POST"
//parameters
let postString = "user_login=(userName)&user_pass=(password)"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) {
data, response, error in guard error == nil else {
print(error!)
completion(nil, error!.localizedDescription)
return
}
guard let data = data else {
completion(nil, "location not found")
return
}
let jsonData = JSON(data)
completion(jsonData, nil)
}
task.resume()
}
}
你的代码对我有用。你记得跑[connection start];
吗?