使用 NSURLConnection 发送 POST 请求

Posted

技术标签:

【中文标题】使用 NSURLConnection 发送 POST 请求【英文标题】:Sending POST request with NSURLConnection 【发布时间】:2012-01-02 12:36:43 【问题描述】:

我正在发送带有请求正文中某些参数的帖子请求。

这是 ios 代码:

 NSURL *url = [NSURL URLWithString:purchaseURL];

 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
 NSString *requestString = [NSString stringWithString:@"userid=1&couponid=1&Ccnum=7b6cd9a44365752cf39c1edf97890b72&Cctype=Visa&Cvv=434&Billingfirstname=Ankit&Billinglastname=Ankit&Street=some&getCity=mycity&State=mystate&getZip=54355&Ccexpmonth=5&Ccexpyear=2012&Phone=43423342"];
NSMutableData *postData=[NSMutableData data];
[postData appendData:[requestString dataUsingEncoding:NSUTF8StringEncoding]];

[request setHTTPMethod:@"POST"];
[request setValue:[NSString stringWithFormat:@"%d", [postData length]] forHTTPHeaderField:@"Content-Length"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];

NSLog(@"content length %d",[postData length]);
[request setValue:@"text/html" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];


NSLog(@"purchage url string %@",postData);

connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];


  NSAssert(self.connection != nil, @"Failure to create URL connection.");

这是处理 post 请求的 php 文件。它处理输入,响应为 JSON 格式。

 public function restpurchaseAction(Request $request)
 

    $userid = $_POST['userid'];
    $couponid = $POST['couponid'];



    //Check that email was verified
//Get the user object to compare id to the listed deals id
if(!$user->getEmailVerified())

    return "Error:  Must verify email before making a purchase.";



// Initialize error varible
$error = "";


//get the currently logged in user
$repository = $this->getDoctrine()
        ->getRepository('FrontendUserBundle:User');
        $user = $repository->findOneByUsername($userid);
//get the coupon that is being purchased
$repository = $this->getDoctrine()
    ->getRepository('FrontendUserBundle:Coupon');
    $coupon = $repository->findOneById($couponid);        

//get the number of times the user has purchased and compare to maxper
$repository = $this->getDoctrine()
->getRepository('FrontendUserBundle:Purchase');     
//if they have already purchased max, redirect to error page
$purchases = $repository->findByCouponAndUser($coupon->getId(), $user->getId());
if(count($purchases) >= $coupon->getMaxper() && $coupon->getMaxper() != 0)
    "Error: Coupon purchased maximum number of times.";


//get the users profile
$profile = $user->getProfile();

//get the users address
$address = $profile->getAddress();

//initialize the new purchase
$purchase = new Purchase();

//generate the coupon verification code
$currentdate = new \DateTime();
$currentdate->setTimestamp(time());
$interval = new \DateInterval('P'.$coupon->getExpirationdate().'D');
$currentdate->add($interval);
$validationnumber1 = mt_rand(1000000, 9999999);
$validationnumber2 = mt_rand(1000000, 9999999);
$validationnumber = $validationnumber1 . $validationnumber2;

//set up all the values for the purchase object
$purchase->setValidationnumber($validationnumber);
$purchase->setUser($user);
$purchase->setCoupon($coupon);
$purchase->setValid(true);
$purchase->setValidationattempts(1);
$purchase->setExpirationDate($currentdate);
$card = $purchase->getCard();
$card->setCcnum($_POST['Ccnum']);
$card->setCctype($_POST['Cctype']);
$card->setCvv($_POST['Cvv']);
$card->setUserid($user->getId());

//If the form has already been submitted then check if it is a valid CC.  
//If so, then finish the purchase,else return to the start.
if($request->getMethod() == 'POST')
    //Get post variables for credit card.

        //Live Mode Credentials
        define("AUTHORIZENET_API_LOGIN_ID", "**********");
        define("AUTHORIZENET_TRANSACTION_KEY", "***************");
        //Test Mode Credentials
        //define("AUTHORIZENET_API_LOGIN_ID", "*************");
        //define("AUTHORIZENET_TRANSACTION_KEY", "*****************");
        define("AUTHORIZENET_SANDBOX", false);
        $response="declined";

        //Make sure maxlimit hasn't been reached before processing.
        if($coupon->getMaxLimit() == 0 || $coupon->getNumPurchased()<=$coupon-                                                                                                                                     >getMaxLimit())
        

        $sale = new AuthorizeNetAIM;

        /*Input coupon information. */
        $item_id = $coupon->getID();
        $item_name = substr($coupon->getCouponname(), 0, 31);
        $item_description = substr($coupon->getDescription(), 0,255);
        $item_quantity = 1;
        $item_unit_price = $coupon->getPrice();
        $item_taxable = FALSE;
        $billingaddress = $purchase->getBillingaddress();
        $card = $purchase->getCard();

        /*Input customer information. */
        $sale->setField('first_name', $_POST['Billingfirstname']);
        $sale->setField('last_name', $_POST['Billinglastname']);
        $sale->setField('email', $user->getEmail);
        $sale->setField('address', $_POST['Street']);
        $sale->setField('city', $_POST['getCity']);
        $sale->setField('state', $_POST['State']);
        $sale->setField('zip', $_POST['getZip']);
        $sale->setField('phone', $_POST['Phone']);


        /*Add information to the sale */
        $sale->addLineItem($item_id, $item_name, $item_description, $item_quantity, $item_unit_price, $item_taxable);
        $sale->amount = $coupon->getPrice();
        $sale->card_num = $_POST['Ccnum'];
        $sale->exp_date = $_POST['Ccexpmonth'] . '/' . $_POST['Ccexpyear'];
        $sale->setField('card_code', $_POST['Cvv']);

        $response = $sale->authorizeAndCapture();
        if ($response->approved) 
            //Prepersist, make sure to remove CVV, and extra CC digits, only store last 4
            $card->setCvv("");
            $lastfour = substr($card->getCcnum(), -4);
            $card->setCcnum($lastfour);
            $transaction_id = $response->transaction_id;
            $purchase->setId = $transaction_id;
            $coupon->incrementNumPurchased();
            $em = $this->get('doctrine')->getEntityManager();
            $em->persist($purchase);
            $em->persist($coupon);
            $em->flush();
            return "Coupon Purchase Successful!";

    else

        $error = $response->error_message;
     
    
    else

        $error = "Maximum number of coupons already purchased!";

    

 

return $error;



我在代码中找不到错误或任何问题。我也尝试过 ASIHttpRequest/ASIFormDataRequest 但无法让它工作。我调用网络服务的方式有问题吗?

【问题讨论】:

欢迎来到 SO - 你的问题,因为它目前的立场并不容易回答,因为你正在发布包含许多不相关内容的 PHP 代码墙。您也没有告诉我们您发布的数据的结果是什么。您是否尝试过在服务器端简单地记录整个帖子以查看收到的内容?您是否尝试过使用代理(例如 Charles)来监控设备和服务器之间的通信? 我不确定,但请尝试将 NSUTF8StringEncoding 替换为 NSASCIIStringEncoding... 等待! 您在 1 个 POST 请求中直接发布信用卡号及其 CCV 和到期日期?它可能不符合 PCI DSS 标准。 【参考方案1】:

调试此问题的最简单方法是实际检查启动连接时收到的错误或响应类型。为此,我建议您让您的类实现以下委托方法:

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
    NSLog(@"Did fail with error %@" , [error localizedDescription]);


-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    NSHTTPURLResponse *httpResponse;
    httpResponse = (NSHTTPURLResponse *)response;
    int statusCode = [httpResponse statusCode];
    NSLog(@"Status code was %d", statusCode);

希望这能让您更好地了解会发生什么。希望对你有帮助:)

【讨论】:

好的,所以404是服务器端返回的HTTP状态码,所以HTTP-post成功发送到服务器。在服务器端,尝试记录请求参数,并找出它返回 404 给客户端的原因。 @ThomasJohanEggum 404 = 未找到 = 客户端使用的 URL 不正确,可能是拼写错误。 先生,这意味着我调用Web服务的方式是正确的,所以可能是Web服务的问题......?我没有使用 php 的工作经验,它是由其他人编写的。 404 是服务器应用程序在 HTTP 响应包中发送的状态代码。由服务器端代码的开发人员在不同情况下发送正确的 HTTP 响应代码。请阅读w3.org/Protocols/rfc2616/rfc2616-sec10.html 了解 HTTP 响应代码规范。我的问题是 PHP 脚本没有找到您请求的用户,因此发送了 404。您知道服务器端是否有效吗?如果没有,请尝试使用 CURL 或其他一些客户端应用程序生成一个 POST 请求,以测试它是否按您想要的方式工作。希望它有所帮助:)【参考方案2】:

试试下面,它可能对你有帮助......

NSString *purchaseURL=@"your url string inside";

NSString *postString=[NSString stringWithFormat:@"userid=1&couponid=1&Ccnum=7b6cd9a44365752cf39c1edf97890b72&Cctype=Visa&Cvv=434&Billingfirstname=Ankit&Billinglastname=Ankit&Street=some&getCity=mycity&State=mystate&getZip=54355&Ccexpmonth=5&Ccexpyear=2012&Phone=43423342"];

NSData *postData=[postString dataUsingEncoding:NSUTF8StringEncoding];

NSURL *url = [NSURL URLWithString:purchaseURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

[request setHTTPMethod:@"POST"];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
[request setValue:[NSString stringWithFormat:@"%i",postData.length] forHTTPHeaderField:@"Content-Length"];
[request setHTTPShouldHandleCookies:YES];
[request setTimeoutInterval:30];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];

NSError *err=nil;

NSData *responseData=[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&err];
NSString *responseString=[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

NSLog(@"response String is  %@",responseString);

如果仍然会出现错误,请尝试更改帖子字符串,如下所示

    NSMutableDictionary *postDix=[[NSMutableDictionary alloc] init];
[postDix setValue:@"1" forKey:@"userid"];
[postDix setValue:@"7b6cd9a44365752cf39c1edf97890b72" forKey:@"Ccnum"];
[postDix setValue:@"Visa" forKey:@"Cctype"];
[postDix setValue:@"434" forKey:@"Cvv"];
[postDix setValue:@"Ankit" forKey:@"Billingfirstname"];
[postDix setValue:@"Ankit" forKey:@"Billinglastname"];
[postDix setValue:@"some" forKey:@"Street"];
[postDix setValue:@"mycity" forKey:@"getCity"];
[postDix setValue:@"mystate" forKey:@"State"];
[postDix setValue:@"54355" forKey:@"getZip"];
[postDix setValue:@"5" forKey:@"Ccexpmonth"];
[postDix setValue:@"2012" forKey:@"Ccexpyear"];
[postDix setValue:@"43423342" forKey:@"Phone"];

NSString *postString=[NSString stringWithFormat:@"%@", postDix];

或将帖子数据更改为:-

NSMutableDictionary *postDix=[[NSMutableDictionary alloc] init];
[postDix setValue:@"1" forKey:@"userid"];
[postDix setValue:@"7b6cd9a44365752cf39c1edf97890b72" forKey:@"Ccnum"];
[postDix setValue:@"Visa" forKey:@"Cctype"];
[postDix setValue:@"434" forKey:@"Cvv"];
[postDix setValue:@"Ankit" forKey:@"Billingfirstname"];
[postDix setValue:@"Ankit" forKey:@"Billinglastname"];
[postDix setValue:@"some" forKey:@"Street"];
[postDix setValue:@"mycity" forKey:@"getCity"];
[postDix setValue:@"mystate" forKey:@"State"];
[postDix setValue:@"54355" forKey:@"getZip"];
[postDix setValue:@"5" forKey:@"Ccexpmonth"];
[postDix setValue:@"2012" forKey:@"Ccexpyear"];
[postDix setValue:@"43423342" forKey:@"Phone"];

NSMutableData *postData = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:postData];
[archiver encodeObject:postDix forKey:@"json"];
[archiver finishEncoding];

【讨论】:

以上是关于使用 NSURLConnection 发送 POST 请求的主要内容,如果未能解决你的问题,请参考以下文章

使用 NSURLConnection 和 HTTPS 发送 POST

NSURLConnection 发送 GET 请求而不是 POST 请求

OC -网络请求 - NSURLConnection - POST

NSURLConnection发送网络请求

如何从 NSURLConnection 委托发送多个 url 请求?

NSURLConnection发送GET请求