0

在我的应用程序中,我正在尝试向服务器发出 POST 请求以将产品添加到购物车。我的代码如下:

#import "CreateCarriage.h"
#import "NSData+Base64.h"

@implementation CreateCarriage{
    NSMutableData *datas;
    NSString *prodID;
}

- (void)createCarriageWithProductID:(NSString *)productID {
    self.qty = @"1";
    prodID = productID;
    [self sendRequestToURL:self.buyUrl withMethod:@"POST"];
}

- (id)sendRequestToURL:(NSString *)url withMethod:(NSString *)method {
    NSURL *finalUrl;
    if ([method isEqualToString:@"POST"]) {
        finalUrl = [NSURL URLWithString:url];
    } else {
        NSLog(@"Metodo non previsto");
    }
    NSString *post = [NSString stringWithFormat:@"form_key=%@&product=%@&related_product=&qty=%@", self.formKey, prodID, self.qty];
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:finalUrl];
    [request setHTTPMethod:method];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
    [request setHTTPBody:postData];
    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);
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    NSString *username = @"user";
    NSString *password = @"password";

    NSURLCredential *credential = [NSURLCredential credentialWithUser:username
                                                             password:password
                                                          persistence:NSURLCredentialPersistenceForSession];
    [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}
@end

当我运行应用程序并尝试将此产品添加到购物车时,它会显示以下 html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Shopping Cart</title>
<meta name="description" content="Default Description" />
<meta name="keywords" content="Magento, Varien, E-commerce" />
<meta name="robots" content="INDEX,FOLLOW" />
<link rel="icon" href="http://54.204.6.246/magento8/skin/frontend/default/default/favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="http://54.204.6.246/magento8/skin/frontend/default/default/favicon.ico" type="image/x-icon" />
<!--[if lt IE 7]>
<script type="text/javascript">
//<![CDATA[
    var BLANK_URL = 'http://54.204.6.246/magento8/js/blank.html';
    var BLANK_IMG = 'http://54.204.6.246/magento8/js/spacer.gif';
//]]>
</script>
<![endif]-->
<link rel="stylesheet" type="text/css" href="http://54.204.6.246/magento8/skin/frontend/default/default/css/styles.css" media="all" />
<link rel="stylesheet" type="text/css" href="http://54.204.6.246/magento8/skin/frontend/base/default/css/widgets.css" media="all" />
<link rel="stylesheet" type="text/css" href="http://54.204.6.246/magento8/skin/frontend/default/default/css/print.css" media="print" />
<script type="text/javascript" src="http://54.204.6.246/magento8/js/prototype/prototype.js"></script>
<script type="tex
2013-11-14 10:59:52.735 BitmamaShop[1240:70b] t/javascript" src="http://54.204.6.246/magento8/js/lib/ccard.js"></script>
<script type="text/javascript" src="http://54.204.6.246/magento8/js/prototype/validation.js"></script>
<script type="text/javascript" src="http://54.204.6.246/magento8/js/scriptaculous/builder.js"></script>
<script type="text/javascript" src="http://54.204.6.246/magento8/js/scriptaculous/effects.js"></script>
<script type="text/javascript" src="http://54.204.6.246/magento8/js/scriptaculous/dragdrop.js"></script>
<script type="text/javascript" src="http://54.204.6.246/magento8/js/scriptaculous/controls.js"></script>
<script type="text/javascript" src="http://54.204.6.246/magento8/js/scriptaculous/slider.js"></script>
<script type="text/javascript" src="http://54.204.6.246/magento8/js/varien/js.js"></script>
<script type="text/javascript" src="http://54.204.6.246/magento8/js/varien/form.js"></script>
<script type="text/javascript" src="http://54.204.6.246/magento8/js/varien/menu.js"></script>
<script type="text/javascript" src="http://54.204.6.246/magento8/js/mage/translate.js"></script>
<script type="text/javascript" src="http://54.204.6.246/magento8/js/mage/cookies.js"></script>
<script type="text/javascript" src="http://54.204.6.246/magento8/js/varien/weee.js"></script>
<!--[if lt IE 8]>
<link rel="stylesheet" type="text/css" href="http://54.204.6.246/magento8/skin/frontend/default/default/css/styles-ie.css" media="all" />
<![endif]-->
<!--[if lt IE 7]>
<script type="text/javascript" src="http://54.204.6.246/magento8/js/lib/ds-sleight.js"></script>
<script type="text/javascript" src="http://54.204.6.246/magento8/skin/frontend/base/default/js/ie6.js"></script>
<![endif]-->

<script type="text/javascript">
//<![CDATA[
Mage.Cookies.path     = '/magento8';
Mage.Cookies.domain   = '.54.204.6.246';
//]]>
</script>

<script type="text/javascript">
//<![CDATA[
optionalZipCountries = ["HK","IE","MO","PA"];
//]]>
</script>
<script type="text/javascript">//<![CDATA[
        var Translator = new Translate([]);
        //]]></script></head>
<body class=" checkout-cart-index">
<div class="wrapper">
        <noscript>
        <div class="global-site-notice noscript">
            <div class="notice-inner">
                <p>
                    <strong>JavaScript seems to be disabled in your browser.</strong><br />
                    You must have JavaScript enabled in your browser to utilize the functionality of this website.                </p>
            </div>
        </div>
    </noscript>
    <div class="page">
        <div class="header-container">
    <div class="header">
                <a href="http://54.204.6.246/magento8/" title="Magento Commerce" class="logo"><strong>Magento Commerce</strong><img src="http://54.204.6.246/magento8/skin/frontend/default/default/images/logo.gif" alt="Magento Commerce" /></a>
                <div class="quick-access">
            <form id="search_mini_form" action="http://54.204.6.246/magento8/catalogsearch/result/" method="get">
    <div class="form-search">
        <label for="search">Search:</label>
        <input id="search" type="text" name="q" value="" class="input-text" maxlength="128" />
        <button type="submit" title="Search" class="button"><span><span>Search</span></span></button>
        <div id="search_autocomplete" class="search-autocomplete"></div>
        <script type="text/javascript">
        //<![CDATA[
            var searchForm = new Varien.searchForm('search_mini_form', 'search', 'Search entire store here...');
            searchForm.initAutocomplete('http://54.204.6.246/magento8/catalogsearch/ajax/suggest/', 'search_autocomplete');
        //]]>
        </script>
    </div>
</form>
            <p class="welcome-msg">Default welcome msg! </p>
            <ul class="links">
                        <li class="first" ><a href="http://54.204.6.246/magento8/customer/account/" title="My Account" >My Account</a></li>
                                <li ><a href="http://54.204.6.246/magento8/wishlist/" title="My Wishlist" >My Wishlist</a></li>
                                <li ><a href="http://54.204.6.246/magento8/checkout/cart/" title="My Cart" class="top-link-cart">My Cart</a></li>
                                <li ><a href="http://54.204.6.246/magento8/checkout/" title="Checkout" class="top-link-checkout">Checkout</a></li>
                                <li class=" last" ><a href="http://54.204.6.246/magento8/customer/account/login/" title="Log In" >Log In</a></li>
            </ul>
                    </div>
            </div>
</div>
<div class="nav-container">
    <ul id="nav">
        <li  class="level0 nav-1 first last level-top"><a href="http://54.204.6.246/magento8/special-sales.html"  class="level-top" ><span>special_sales</span></a></li>    </ul>
</div>
        <div class="main-container col1-layout">
            <div class="main">
                                <div class="col-main">
                                        <div class="page-title">
    <h1>Shopping Cart is Empty</h1>
</div>
<div class="cart-empty">
            <p>You have no items in your shopping cart.</p>
    <p>Click <a href="http://54.204.6.246/magento8/api/rest/products/1">here</a> to continue shopping.</p>
    </div>
                </div>
            </div>
        </div>
        <div class="footer-container">
    <div class="footer">
        <ul>
<li><a href="http://54.204.6.246/magento8/about-magento-demo-store">About Us</a></li>
<li><a href="http://54.204.6.246/magento8/customer-service">Customer Service</a></li>
<li class="last privacy"><a href="http://54.204.6.246/magento8/privacy-policy-cookie-restriction-mode">Privacy Policy</a></li>
</ul><ul class="links">
                        <li class="first" ><a href="http://54.204.6.246/magento8/catalog/seo_sitemap/category/" title="Site Map" >Site Map</a></li>
                                <li ><a href="http://54.204.6.246/magento8/catalogsearch/term/popular/" title="Search Terms" >Search Terms</a></li>
                                <li ><a href="http://54.204.6.246/magento8/catalogsearch/advanced/" title="Advanced Search" >Advanced Search</a></li>
                                <li ><a href="http://54.204.6.246/magento8/sales/guest/form/" title="Orders and Returns" >Orders and Returns</a></li>
                                <li class=" last" ><a href="http://54.204.6.246/magento8/contacts/" title="Contact Us" >Contact Us</a></li>
            </ul>
        <p class="bugs">Help Us to Keep Magento Healthy - <a href="http://www.magentocommerce.com/bug-tracking" onclick="this.target='_blank'"><strong>Report All Bugs</strong></a> (ver. 1.8.0.0)</p>
        <address>&copy; 2013 Magento Demo Store. All Rights Reserved.</address>
    </div>
</div>
            </div>
</div>
</body>
</html>

您可以在其中看到我没有在我的购物车中添加任何东西......这段代码有什么问题?

更新:

我尝试使用 Chrome 来查看浏览器所做的 POST/GET 请求,我将在此处发布响应:

Request URL:http://54.204.6.246/magento8/checkout/cart/add/uenc/aHR0cDovLzU0LjIwNC42LjI0Ni9tYWdlbnRvOC9zcGVjaWFsLXNhbGVzL2VhdS1kZS10b2lsZXQtMi5odG1sP19fX1NJRD1V/product/2/form_key/7CUKq8086ReKwIjs/
Request Method:POST
Status Code:302 Moved Temporarily
Request Headersview source
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip,deflate,sdch
Accept-Language:it-IT,it;q=0.8,en-US;q=0.6,en;q=0.4
Authorization:Basic cmVwbHk6cmVwbHk=
Cache-Control:max-age=0
Content-Length:58
Content-Type:application/x-www-form-urlencoded
Cookie:PHPSESSID=hsbbokn9h4v0dnaa3oiis38jd5; frontend=8u4mii1suojhhmj27ndiqm4pf3
Host:54.204.6.246
Origin:http://54.204.6.246
Proxy-Connection:keep-alive
Referer:http://54.204.6.246/magento8/special-sales/eau-de-toilet-2.html
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.48 Safari/537.36
Form Dataview parsed
form_key=7CUKq8086ReKwIjs&product=2&related_product=&qty=1
Response Headersview source
Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection:keep-alive
Content-Length:0
Content-Type:text/html; charset=UTF-8
Date:Thu, 14 Nov 2013 09:35:13 GMT
Expires:Thu, 19 Nov 1981 08:52:00 GMT
Location:http://54.204.6.246/magento8/checkout/cart/
Pragma:no-cache
Server:Apache/2.2.15 (Red Hat)
Set-Cookie:frontend=8u4mii1suojhhmj27ndiqm4pf3; expires=Thu, 14-Nov-2013 10:35:14 GMT; Max-Age=3600; path=/magento8; domain=54.204.6.246; httponly
Via:1.1 ced01squidp02.replynet.prv (squid/3.3.9)
X-Cache:MISS from ced01squidp02.replynet.prv
X-Cache-Lookup:MISS from ced01squidp02.replynet.prv:8080
X-Powered-By:PHP/5.5.5

我想我应该使用它的部分,Form Data它向我展示了这个请求:form_key=7CUKq8086ReKwIjs&product=2&related_product=&qty=1如果你看一下我的 iOS 代码,你会发现我试图做同样的事情。

4

1 回答 1

0

My advice is to create an API and use that API for accessing through any other device. But if you want to use the existing Magento website to make posts and create cart items;

  • Use Google Chrome
  • Go to the product page.
  • Right click anywhere and select "Inspect Element"
  • Go to the "Network" tab on the Developer tools pane (bottom pane that opens when you click"Inspect Element").
  • Add the product to the cart. At this point you will see the request on "Network" tab.
  • Select the request from the list and select "Headers" tab there. You will see the used URL and the POST/GET parameters, and also the cookies that was used. Try to replicate every querystring/post parameter in your code.

Above investigation always gives me more insight into the request. So that you can replicate the same GET/POST request.

Just remember; Magento may change the fields and the structure of the product and if you upgrade to a later version in the future, your code might not work.

One ather advice; use AFNetworking for your HTTP calls. It works great for me.

Cheers. Uygar

于 2013-11-14T10:17:17.793 回答