2012-01-02 155 views
3

我正在發送請求與請求正文中的某個參數。使用NSURLConnection發送POST請求

這裏是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."); 

這是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,但無法讓它工作。我在調用Web服務的方式有問題嗎?

+3

歡迎來到SO - 您的問題,因爲它目前的立場是不容易回答,因爲你正在張貼的PHP代碼續牆發現了很多不相關的東西。您也不會告訴我們發佈數據的結果。你有沒有試圖簡單地在服務器端登錄整篇文章來查看收到的內容?您是否嘗試過使用代理(例如Charles)來監控設備和服務器之間的通信? – Till 2012-01-02 12:46:03

+0

我不確定,但嘗試使用NSASCIIStringEncoding替換NSUTF8StringEncoding ... – 2012-01-02 12:50:39

+0

**等待!**您直接在其單個POST請求中發送信用卡號碼及其CCV和失效日期?它可能不符合PCI DSS標準。 – Raptor 2013-05-24 04:09:12

回答

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); 
} 

希望這將讓你發生了什麼更好的主意。希望它能幫助:)

+0

約翰,先生,我已經試過使用它,它返回我404 – ankit 2012-01-02 13:01:32

+0

@ankit請參閱http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html – Till 2012-01-02 13:12:51

+0

好吧,所以404是從服務器返回的HTTP狀態代碼所以HTTP-post被成功發送到服務器。 在服務器端,嘗試記錄請求參數,並找出爲什麼它返回404到客戶端。 – 2012-01-02 13:19:04

0

下面嘗試,它可以幫助你......

NSString *[email protected]"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];