Cómo enviar CORREO y OBTENER solicitud?
Quiero enviar mi JSON
a una URL (POST
y GET
).
NSMutableDictionary *JSONDict = [[NSMutableDictionary alloc] init];
[JSONDict setValue:"myValue" forKey:"myKey"];
NSData *JSONData = [NSJSONSerialization dataWithJSONObject:self options:kNilOptions error:nil];
Mi código de solicitud actual no funciona.
NSMutableURLRequest *requestData = [[NSMutableURLRequest alloc] init];
[requestData setURL:[NSURL URLWithString:@"http://fake.url/"];];
[requestData setHTTPMethod:@"POST"];
[requestData setValue:postLength forHTTPHeaderField:@"Content-Length"];
[requestData setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[requestData setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[requestData setHTTPBody:postData];
Usar ASIHTTPRequest
es no una respuesta responsable.
5 answers
Enviar solicitudes POST
y GET
en iOS es bastante fácil; y no hay necesidad de un marco adicional.
POST
Solicitud:
Comenzamos creando nuestros POST
's body
(ergo. lo que nos gustaría enviar) como NSString
, y convertirlo a NSData
.
NSString *post = [NSString stringWithFormat:@"test=Message&this=isNotReal"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
A continuación, leemos los postData
's length
, para que podamos pasarlo en la solicitud.
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
Ahora que tenemos lo que nos gustaría publicar, podemos crear un NSMutableURLRequest
, e incluir nuestro postData
.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://YourURL.com/FakeURL"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postData];
let post = "test=Message&this=isNotReal"
let postData = post.data(using: String.Encoding.ascii, allowLossyConversion: true)
let postLength = String(postData!.count)
var request = URLRequest(url: URL(string: "http://YourURL.com/FakeURL/PARAMETERS")!)
request.httpMethod = "POST"
request.addValue(postLength, forHTTPHeaderField: "Content-Length")
request.httpBody = postData;
Y finalmente, podemos enviar nuestra solicitud, y leer la respuesta creando un nuevo NSURLSession
:
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(@"Request reply: %@", requestReply);
}] resume];
let session = URLSession(configuration: .default)
session.dataTask(with: request) {data, response, error in
let requestReply = NSString(data: data!, encoding: String.Encoding.ascii.rawValue)
print("Request reply: \(requestReply!)")
}.resume()
GET
Solicitud:
Con la solicitud GET
es básicamente lo mismo, solo que sin el HTTPBody
y Content-Length
.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://YourURL.com/FakeURL/PARAMETERS"]];
[request setHTTPMethod:@"GET"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(@"Request reply: %@", requestReply);
}] resume];
var request = URLRequest(url: URL(string: "http://YourURL.com/FakeURL/PARAMETERS")!)
request.httpMethod = "GET"
let session = URLSession(configuration: .default)
session.dataTask(with: request) {data, response, error in
let requestReply = NSString(data: data!, encoding: String.Encoding.ascii.rawValue)
print("Request reply: \(requestReply!)")
}.resume()
En una nota al margen, puede agregar Content-Type
(y otros datos) agregando lo siguiente a nuestro NSMutableURLRequest
. Esto puede ser requerido por el servidor cuando se solicita, por ejemplo, un json.
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
El código de respuesta también se puede leer usando [(NSHTTPURLResponse*)response statusCode]
.
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
Actualización: sendSynchronousRequest
es obsoleto de ios9 y osx-elcapitan (10.11) y fuera.
NSURLResponse *requestResponse; NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request returningResponse:&requestResponse error:nil]; NSString *requestReply = [[NSString alloc] initWithBytes:[requestHandler bytes] length:[requestHandler length] encoding:NSASCIIStringEncoding]; NSLog(@"requestReply: %@", requestReply);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-20 14:40:35
Usando RestKit puede hacer una simple solicitud POST (vea esta página GitHub para más detalles).
Importa RestKit en tu archivo de cabecera.
#import <RestKit/RestKit.h>
Luego puede comenzar creando un nuevo RKRequest
.
RKRequest *MyRequest = [[RKRequest alloc] initWithURL:[[NSURL alloc] initWithString:@"http://myurl.com/FakeUrl/"]];
Luego especifique qué tipo de solicitud desea realizar (en este caso, una solicitud POST
).
MyRequest.method = RKRequestMethodPOST;
MyRequest.HTTPBodyString = YourPostString;
Y luego establece tu solicitud como JSON en additionalHTTPHeaders
.
MyRequest.additionalHTTPHeaders = [[NSDictionary alloc] initWithObjectsAndKeys:@"application/json", @"Content-Type", @"application/json", @"Accept", nil];
Finalmente, puede enviar el solicitud.
[MyRequest send];
Además puede NSLog
su solicitud para ver el resultado.
RKResponse *Response = [MyRequest sendSynchronously];
NSLog(@"%@", Response.bodyAsString);
Fuentes: RestKit.org y Me.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:10:38
-(void)postmethod
{
NSString * post =[NSString stringWithFormat:@"Email=%@&Password=%@",_txt_uname.text,_txt_pwd.text];
NSData *postdata= [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength=[NSString stringWithFormat:@"%lu",(unsigned long)[postdata length]];
NSMutableURLRequest *request= [[NSMutableURLRequest alloc]init];
NSLog(@"%@",app.mainurl);
// NSString *str=[NSString stringWithFormat:@"%@Auth/Login",app.mainurl];
NSString *str=YOUR URL;
[request setURL:[NSURL URLWithString:str]];
[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 *returnstring=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSMutableDictionary *dict=[returnstring JSONValue];
NSLog(@"%@",dict);
}
-(void)GETMethod
{
NSString *appurl;
NSString *temp =@"YOUR URL";
appurl = [NSString stringWithFormat:@"%@uid=%@&cid=%ld",temp,user_id,(long)clubeid];
appurl = [appurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:appurl]];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse: nil error: nil ];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSMutableDictionary *dict_eventalldata=[returnString JSONValue];
NSString *success=[dict_eventalldata objectForKey:@"success"];
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-07 10:21:36
Solicitud Get:
-(void)fetchData{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL:[NSURL
URLWithString:@"yourURL"]];
NSLog(@"LatestURL:%@",data);
NSError* error=nil;
NSDictionary *jsonDict= [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions error:&error];
NSLog(@"JSON = %@", [[NSString alloc] initWithData:data encoding:
NSUTF8StringEncoding]);
dispatch_async(dispatch_get_main_queue(), ^{
NSDictionary *statuses=[jsonDict objectForKey:@"result"];
NSLog(@"SomeStatus :%@",statuses);
if (!statuses)
{
NSLog(@"Error in Json :%@",error);
}
else
{
[self.arrayTimeline removeAllObjects];
for(NSDictionary *newValu in statuses)
{
[self.arrayTimeline addObject:newValu];
NSString *ProjectName=[newValu objectForKey:@"project_name"];
NSLog(@"Project Name : %@",ProjectName);
NSString *Stage=[newValu objectForKey:@"stage_name"];
NSLog(@"Stage : %@",Stage);
NSString *CompTime=[newValu objectForKey:@"completion_time"];
NSLog(@"Completion Time : %@",CompTime);
NSString *Status=[newValu objectForKey:@"status"];
NSLog(@"Status : %@",Status);
}
[self.projectTimelineTable reloadData];
});
} }); }
Respuesta JSON: {"status":"success","name":"project1","address":"badkal mor metro station", "state": "haryana", "city": "faridabad", "start_time":"1480586013","current_stage":"Tender Acceptance","manager":"Not Available"," completion_time": "1480464000"}
Puede obtener el valor de las claves como name, start_time, etc. y mostrar en la etiqueta
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-30 09:12:20
Control de vista.h
@interface ViewController UIViewController<UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong,nonatomic)NSArray *array;
@property NSInteger select;
@end
Vista.m
- (void)viewDidLoad {
[super viewDidLoad];
NSString *urlString = [NSString stringWithFormat: @"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=11.021459,76.916332&radius=2000&types=atm&sensor=false&key=AIzaS yD7c1IID7zDCdcfpC69fC7CUqLjz50mcls"];
NSURL *url = [NSURL URLWithString: urlString];
NSData *data = [NSData dataWithContentsOfURL:url];
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:
data options: 0 error: nil];
_array = [[NSMutableArray alloc]init];
_array = [[jsonData objectForKey:@"results"] mutableCopy];
[_tableView reloadData];}
// Do any additional setup after loading the view, typically from a
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
return _array.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellid = @"cell";
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:cellid];
cell = [[UITableViewCell
alloc]initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:cellid];
cell.textLabel.text = [[_array
valueForKeyPath:@"name"]objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [[_array
valueForKeyPath:@"vicinity"]objectAtIndex:indexPath.row];
NSURL *imgUrl = [NSURL URLWithString:[[_array
valueForKey:@"icon"]objectAtIndex:indexPath.row]];
NSData *imgData = [NSData dataWithContentsOfURL:imgUrl];
cell.imageView.layer.cornerRadius =
cell.imageView.frame.size.width/2;
cell.imageView.layer.masksToBounds = YES;
cell.imageView.image = [UIImage imageWithData:imgData];
return cell;
}
@end
Tablecell.h
@interface TableViewCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UIImageView *imgView;
@property (weak, nonatomic) IBOutlet UILabel *lblName;
@property (weak, nonatomic) IBOutlet UILabel *lblAddress;
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-08 09:11:55