HTTPS POST成功运行但变量为空

时间:2017-07-25 22:44:50

标签: php ios swift post server

我在这里发布的代码是一个缩短版本,只包含问题的基本要点。在进行严格的错误测试时,似乎在请求内,服务器内或返回代码中都没有问题,除了来自服务器的响应显示“Function”的事实:null而不是“Function” :“addUser”应该如此。在两端都有我做错的事吗?它似乎没有识别发布的变量,但我已经在其他应用程序和服务器中多次使用此代码,并且由于某些我无法看到的原因,它似乎失败了。感谢您的帮助。

这是我在服务器上的PHP:

<?php
   $t = $_POST["function"];
   $do = array("Success"=>true, "Function"=> $t);
   echo json_encode($do);
?>

以下是我用来提出请求的快捷方式:

  let params = ["function": "addUser"] as [String: AnyObject]?


    fetchData("https://pdt.pitchprogress.net/SamplePHP.php", token: nil, parameters: params, method: "POST", onCompletion: { (success, data) -> Void in
        if success {
            do {
                let json = try JSON(data: data!)
                if json["Success"].boolValue == true {
                    print("success!")
                    print(json.description)
                    print(json["Function"].stringValue)
               }
              }      
             }       
             })       




func fetchData(_ feed:String,token:String? = nil,parameters:[String:AnyObject]? = nil,method:String? = nil, onCompletion:@escaping (_ success:Bool,_ data:Data?)->Void){

DispatchQueue.main.async {


    if let unwrapped_url = URL(string: feed){
        let request = NSMutableURLRequest(url: unwrapped_url)

        if let parm = parameters {
            if let data = (try? JSONSerialization.data(withJSONObject: parm, options:[])) as Data? {

                request.httpBody = data
                request.setValue("application/json", forHTTPHeaderField: "Content-Type")
                request.setValue("\(data.count)", forHTTPHeaderField: "Content-Length")

            }
        }

        if let unwrapped_method = method {
            request.httpMethod = unwrapped_method
        }

        let sessionConfiguration = URLSessionConfiguration.default
        sessionConfiguration.timeoutIntervalForRequest = 15.0
        let session = URLSession(configuration: sessionConfiguration)

        let taskGetCategories = session.dataTask(with: request as URLRequest, completionHandler: { (responseData, response, error) -> Void in

            let statusCode = (response as! HTTPURLResponse?)?.statusCode
            //println("Status Code: \(statusCode), error: \(error)")
            if error != nil || (statusCode != 200 && statusCode != 201 && statusCode != 202){
                onCompletion(false, nil)

            } else {
                onCompletion(true, responseData)
            }
        })

        taskGetCategories.resume()
    }
}
}

2 个答案:

答案 0 :(得分:0)

看起来您的密钥使用不同&#34;功能&#34;而不是使用&#34;功能&#34;

答案 1 :(得分:0)

这是因为您将params作为JSON发送,而您的API需要params作为表单数据。

此代码将params作为简单的表单发送,并检索成功的响应。

/**
 * Uses a combination of a PageTransformer and swapping X & Y coordinates
 * of touch events to create the illusion of a vertically scrolling ViewPager. 
 * 
 * Requires API 11+
 * 
 */
public class VerticalViewPager extends ViewPager {

    public VerticalViewPager(Context context) {
        super(context);
        init();
    }

    public VerticalViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        // The majority of the magic happens here
        setPageTransformer(true, new VerticalPageTransformer());
        // The easiest way to get rid of the overscroll drawing that happens on the left and right
        setOverScrollMode(OVER_SCROLL_NEVER);
    }

    private class VerticalPageTransformer implements ViewPager.PageTransformer {

        @Override
        public void transformPage(View view, float position) {

            if (position < -1) { // [-Infinity,-1)
                // This page is way off-screen to the left.
                view.setAlpha(0);

            } else if (position <= 1) { // [-1,1]
                view.setAlpha(1);

                // Counteract the default slide transition
                view.setTranslationX(view.getWidth() * -position);

                //set Y position to swipe in from top
                float yPosition = position * view.getHeight();
                view.setTranslationY(yPosition);

            } else { // (1,+Infinity]
                // This page is way off-screen to the right.
                view.setAlpha(0);
            }
        }
    }

    /**
     * Swaps the X and Y coordinates of your touch event.
     */
    private MotionEvent swapXY(MotionEvent ev) {
        float width = getWidth();
        float height = getHeight();

        float newX = (ev.getY() / height) * width;
        float newY = (ev.getX() / width) * height;

        ev.setLocation(newX, newY);

        return ev;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev){
        boolean intercepted = super.onInterceptTouchEvent(swapXY(ev));
        swapXY(ev); // return touch coordinates to original reference frame for any child views
        return intercepted;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        return super.onTouchEvent(swapXY(ev));
    }

}

我曾经做过一个小包装来发送简单的表单数据,如果我发现它,我会用它来更新答案。直到那时你可以试试这个。让我知道它是怎么回事......