ios – POST请求使用application / x-www-form-urlencoded

前端之家收集整理的这篇文章主要介绍了ios – POST请求使用application / x-www-form-urlencoded前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
后端开发人员在POST请求中给出了这些说明:

>路线:{url} / {app_name / {controller} / {action}
控制器和动作应该是小帽子.
> API测试链接:http:****************
>请求应该使用POST方法.
>参数应通过请求内容体(FormUrlEncodedContent)传递.
>参数应该是json格式.
>参数是关键的.

在协议中没有经验5,我搜索并结束了我的代码.

  1. -(id)initWithURLString:(NSString *)URLString withHTTPMEthod:(NSString *)method withHTTPBody:(NSDictionary *)body {
  2.  
  3. _URLString = URLString;
  4. HTTPMethod = method;
  5. HTTPBody = body;
  6.  
  7. //set error message
  8. errorMessage = @"Can't connect to server at this moment. Try again later";
  9. errorTitle = @"Connection Error";
  10.  
  11. return self;
  12. }
  13.  
  14.  
  15. -(void)fireConnectionRequest {
  16.  
  17. NSOperationQueue *mainQueue = [[NSOperationQueue alloc] init];
  18. [mainQueue setMaxConcurrentOperationCount:5];
  19.  
  20. NSError *error = Nil;
  21.  
  22. NSURL *url = [NSURL URLWithString:_URLString];
  23. NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
  24.  
  25. NSData *sendData = [NSJSONSerialization dataWithJSONObject:HTTPBody options:NSJSONWritingPrettyPrinted error:&error];
  26. [request setHTTPMethod:@"POST"];
  27.  
  28. [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
  29. [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
  30.  
  31. [request setHTTPBody: sendData];
  32. [NSURLConnection connectionWithRequest:request delegate:self];
  33.  
  34. NSString *jsonString = [[NSString alloc]initWithData:sendData encoding:NSUTF8StringEncoding];
  35.  
  36.  
  37. //fire URL connectiion request
  38. [NSURLConnection sendAsynchronousRequest:request queue:mainQueue completionHandler:^(NSURLResponse *response,NSData *responseData,NSError *error) {
  39.  
  40. //get the return message and transform to dictionary
  41. NSString *data = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
  42. returnMessage = [NSJSONSerialization JSONObjectWithData: [data dataUsingEncoding:NSUTF8StringEncoding]
  43. options: NSJSONReadingMutableContainers
  44. error:&error];
  45.  
  46.  
  47. //check return message
  48. if (!error) {
  49. [delegate returnMessageForTag:self.tag];
  50.  
  51. }
  52. else {
  53. [delegate returnErrorMessageForTag:self.tag];
  54. }
  55.  
  56. }];
  57.  
  58. }

我传递格式为JSON的字典.他同意我能够传递正确的数据.我可以连接到API,但是当我尝试发送数据进行注册时总是返回“Failed”.没有连接问题,但是我没有传输数据.

这里的Android开发人员使用相同的API没有问题,但是由于他不熟悉iOS,所以无法帮助我.

我失踪了什么

解决方法

尝试这样的代码

目标C

  1. NSString *post =[NSString stringWithFormat:@"AgencyId=1&UserId=1&Type=1&Date=%@&Time=%@&Coords=%@&Image=h32979`7~U@)01123737373773&SeverityLevel=2",strDateLocal,strDateTime,dict];
  2. NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
  3. NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
  4. NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
  5. [request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://google/places"]]];
  6. [request setHTTPMethod:@"POST"];
  7. [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
  8. [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
  9. [request setHTTPBody:postData];
  10. NSError *error;
  11. NSURLResponse *response;
  12. NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
  13. NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];

Swift 2.2

  1. var post = "AgencyId=1&UserId=1&Type=1&Date=\(strDateLocal)&Time=\(strDateTime)&Coords=\(dict)&Image=h32979`7~U@)01123737373773&SeverityLevel=2"
  2. var postData = post.dataUsingEncoding(NSASCIIStringEncoding,allowLossyConversion: true)!
  3. var postLength = "\(postData.length)"
  4. var request = NSMutableURLRequest()
  5. request.URL = NSURL(string: "http://google/places")!
  6. request.HTTPMethod = "POST"
  7. request.setValue(postLength,forHTTPHeaderField: "Content-Length")
  8. request.setValue("application/x-www-form-urlencoded",forHTTPHeaderField: "Content-Type")
  9. request.HTTPBody = postData
  10. NSError * error
  11. NSURLResponse * response
  12. var urlData = try! NSURLConnection.sendSynchronousRequest(request,returningResponse: response)!
  13. var str = String(data: urlData,encoding: NSUTF8StringEncoding)

Swift 3.0

  1. let jsonData = try? JSONSerialization.data(withJSONObject: kParameters)
  2. let url: URL = URL(string: "Add Your API URL HERE")!
  3. print(url)
  4. var request: URLRequest = URLRequest(url: url)
  5. request.httpMethod = "POST"
  6. request.httpBody = jsonData
  7. request.setValue(Constant.UserDefaults.object(forKey: "Authorization") as! String?,forHTTPHeaderField: "Authorization")
  8. request.setValue(Constant.kAppContentType,forHTTPHeaderField: "Content-Type")
  9. request.setValue(Constant.UserAgentFormat(),forHTTPHeaderField: "User-Agent")
  10.  
  11. let task = URLSession.shared.dataTask(with: request,completionHandler: { data,response,error in
  12.  
  13. if data != nil {
  14.  
  15. do {
  16. let json = try JSONSerialization.jsonObject(with: data!,options: .allowFragments) as! NSDictionary
  17. print(json)
  18. } catch let error as NSError {
  19. print(error)
  20. }
  21. } else {
  22. let emptyDict = NSDictionary()
  23. }
  24. })
  25. task.resume()

我希望这段代码对你有用.

猜你在找的iOS相关文章