后端开发人员在POST请求中给出了这些说明:
>路线:{url} / {app_name / {controller} / {action}
控制器和动作应该是小帽子.
> API测试链接:http:****************
>请求应该使用POST方法.
>参数应通过请求内容体(FormUrlEncodedContent)传递.
>参数应该是json格式.
>参数是关键的.
在协议中没有经验5,我搜索并结束了我的代码.
-(id)initWithURLString:(Nsstring *)URLString withHTTPMEthod:(Nsstring *)method withHTTPBody:(NSDictionary *)body { _URLString = URLString; HTTPMethod = method; HTTPBody = body; //set error message errorMessage = @"Can't connect to server at this moment. Try again later"; errorTitle = @"Connection Error"; return self; } -(void)fireConnectionRequest { NSOperationQueue *mainQueue = [[NSOperationQueue alloc] init]; [mainQueue setMaxConcurrentOperationCount:5]; NSError *error = Nil; NSURL *url = [NSURL URLWithString:_URLString]; NSMutableuRLRequest *request = [[NSMutableuRLRequest alloc] initWithURL:url]; NSData *sendData = [NSJSONSerialization dataWithJSONObject:HTTPBody options:NSJSONWritingPrettyPrinted error:&error]; [request setHTTPMethod:@"POST"]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; [request setHTTPBody: sendData]; [NSURLConnection connectionWithRequest:request delegate:self]; Nsstring *jsonString = [[Nsstring alloc]initWithData:sendData encoding:NSUTF8StringEncoding]; //fire URL connectiion request [NSURLConnection sendAsynchronousRequest:request queue:mainQueue completionHandler:^(NSURLResponse *response,NSData *responseData,NSError *error) { //get the return message and transform to dictionary Nsstring *data = [[Nsstring alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; returnMessage = [NSJSONSerialization JSONObjectWithData: [data dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableContainers error:&error]; //check return message if (!error) { [delegate returnMessageForTag:self.tag]; } else { [delegate returnErrorMessageForTag:self.tag]; } }]; }
我传递格式为JSON的字典.他同意我能够传递正确的数据.我可以连接到API,但是当我尝试发送数据进行注册时总是返回“Failed”.没有连接问题,但是我没有传输数据.
这里的Android开发人员使用相同的API没有问题,但是由于他不熟悉iOS,所以无法帮助我.
我失踪了什么
解决方法
尝试这样的代码
目标C
Nsstring *post =[Nsstring stringWithFormat:@"AgencyId=1&UserId=1&Type=1&Date=%@&Time=%@&Coords=%@&Image=h32979`7~U@)01123737373773&SeverityLevel=2",strDateLocal,strDateTime,dict]; NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; Nsstring *postLength = [Nsstring stringWithFormat:@"%d",[postData length]]; NSMutableuRLRequest *request = [[[NSMutableuRLRequest alloc] init] autorelease]; [request setURL:[NSURL URLWithString:[Nsstring stringWithFormat:@"http://google/places"]]]; [request setHTTPMethod:@"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:postData]; NSError *error; NSURLResponse *response; NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; Nsstring *str=[[Nsstring alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
Swift 2.2
var post = "AgencyId=1&UserId=1&Type=1&Date=\(strDateLocal)&Time=\(strDateTime)&Coords=\(dict)&Image=h32979`7~U@)01123737373773&SeverityLevel=2" var postData = post.dataUsingEncoding(NSASCIIStringEncoding,allowLossyConversion: true)! var postLength = "\(postData.length)" var request = NSMutableuRLRequest() request.URL = NSURL(string: "http://google/places")! request.HTTPMethod = "POST" request.setValue(postLength,forHTTPHeaderField: "Content-Length") request.setValue("application/x-www-form-urlencoded",forHTTPHeaderField: "Content-Type") request.HTTPBody = postData NSError * error NSURLResponse * response var urlData = try! NSURLConnection.sendSynchronousRequest(request,returningResponse: response)! var str = String(data: urlData,encoding: NSUTF8StringEncoding)
Swift 3.0
let jsonData = try? JSONSerialization.data(withJSONObject: kParameters) let url: URL = URL(string: "Add Your API URL HERE")! print(url) var request: URLRequest = URLRequest(url: url) request.httpMethod = "POST" request.httpBody = jsonData request.setValue(Constant.UserDefaults.object(forKey: "Authorization") as! String?,forHTTPHeaderField: "Authorization") request.setValue(Constant.kAppContentType,forHTTPHeaderField: "Content-Type") request.setValue(Constant.UserAgentFormat(),forHTTPHeaderField: "User-Agent") let task = URLSession.shared.dataTask(with: request,completionHandler: { data,response,error in if data != nil { do { let json = try JSONSerialization.jsonObject(with: data!,options: .allowFragments) as! NSDictionary print(json) } catch let error as NSError { print(error) } } else { let emptyDict = NSDictionary() } }) task.resume()
我希望这段代码对你有用.