在我的应用程序中,我将向远程 Magento 购物车添加一个对象。所以我的应用程序有一个,我可以viewController
在其中选择我想要的产品,当我点击该产品时,它会向我展示另一个viewController
,我可以在其中阅读产品的详细信息。现在我在其中放了一个按钮viewController
来将产品添加到购物车。我在浏览器上尝试了Magento
电子商务,我看到当我单击“添加到购物车”按钮时,它会使用以下地址向服务器发送一个 http 请求:
http://54.204.6.246/magento8/checkout/cart/add/uenc/aHR0cDovLzU0LjIwNC42LjI0Ni9tYWdlbnRvOC9zcGVjaWFsLXNhbGVzLmh0bWw,/product/1/form_key/Zqmpp3fnpuTtxI4b/
这样我就将产品放入了远程购物车Magento
。现在我想对我的iOS
应用程序做同样的事情,所以我写了以下代码:
#import "CreateCarriage.h"
#import "NSData+Base64.h"
@implementation CreateCarriage{
NSMutableData *datas;
}
- (void)createCarriageWithProductID:(NSString *)productID {
NSString *addProductLink = [NSString stringWithFormat:@"http://54.204.6.246/magento8/checkout/cart/add/uenc/aHR0cDovLzU0LjIwNC42LjI0Ni9tYWdlbnRvOC9zcGVjaWFsLXNhbGVzLmh0bWw,/product/%@/form_key/Zqmpp3fnpuTtxI4b/", productID];
[self sendRequestToURL:addProductLink withMethod:@"GET"];
}
- (id)sendRequestToURL:(NSString *)url withMethod:(NSString *)method {
NSURL *finalUrl;
if ([method isEqualToString:@"GET"]) {
finalUrl = [NSURL URLWithString:url];
} else {
NSLog(@"Metodo non previsto");
}
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:finalUrl];
[request setHTTPMethod:method];
NSString *authStr = @"user:password";
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64EncodedString]];
[request setValue:authValue forHTTPHeaderField:@"Authorization"];
// [request setValue:@"x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-type"];
NSLog(@"%@", request);
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
if (connection) {
[connection start];
}
return connection;
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
datas = [[NSMutableData alloc]init];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
[datas appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"Oggetto aggiunto al carrello");
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"%@", error);
}
@end
但是当我运行该应用程序时,它会向我显示:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<head>
<title>401 Authorization Required</title>
</head>
<body>
<h1>Authorization Required</h1>
<p>This server could not verify that you are authorized to access the document requested. Either you supplied the wrong credentials (e.g., bad password), or your browser doesn't understand how to supply the credentials required.</p>
<hr>
<address>Apache/2.2.15 (Red Hat) Server at 54.204.6.246 Port 80</address>
</body>
</html>
我的代码有什么问题?如果我在正常浏览器上尝试它们,我在代码中设置的用户和密码确实是正确的。