如何在swift中使用HTTP PUT方法进行rest api调用

时间:2016-05-24 12:10:10

标签: ios swift restkit put

我已使用REST Api方法尝试了以下PUT

这是我的代码,

let url = NSURL(string: "http://sampleurl")

let request = NSMutableURLRequest(URL: url!)

request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") 

request.HTTPMethod = "PUT"

let session = NSURLSession(configuration:NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: nil, delegateQueue: nil)

let params:[String: AnyObject] = ["deviceId" : "device_1","mobileDeviceId" : "abcd","deviceType":"ios"]

request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions(), error: nil)

let dataTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in

        if error != nil {

            //handle error

             print("Parsed error: '\(error)'")
        }
        else {

            let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("Parsed JSON: '\(jsonStr)'")
        } 
    }
dataTask.resume()

它不起作用。请帮我找出错误的地方。

3 个答案:

答案 0 :(得分:1)

这是一个有效的代码,我将字典作为JSON格式的字符串发送到服务器,在服务器中,我解析请求并构建另一个包含与请求相同值的JSON对象,并将它们发送回该应用程序。在应用程序中,我解析响应并打印结果:

 let session = NSURLSession.sharedSession()
            let url = "http://localhost:8080/yourServerGoesHere/putMethodTest"
            let request = NSMutableURLRequest(URL: NSURL(string: url)!)
            request.HTTPMethod = "PUT"

            let params:[String: AnyObject] = ["deviceId" : "device_1","mobileDeviceId" : "abcd","deviceType":"ios"]
            do{
                request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions())
                let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
                    if let response = response {
                        let nsHTTPResponse = response as! NSHTTPURLResponse
                        let statusCode = nsHTTPResponse.statusCode
                        print ("status code = \(statusCode)")
                    }
                    if let error = error {
                        print ("\(error)")
                    }
                    if let data = data {
                        do{
                        let jsonData = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions())
                        let deviceId = jsonData["deviceId"] as! String
                        let mobileDeviceId = jsonData["mobileDeviceId"] as! String
                        let deviceType = jsonData["deviceType"] as! String
                        print (" deviceId= \(deviceId), mobileDeviceId= \(mobileDeviceId), deviceType= \(deviceType)")
                        }catch _ {
                            print ("the response is not well JSON formatted")
                        }
                    }
                })
                task.resume()
            }catch _ {
                print ("Oops something happened buddy")
            }

如果您想尝试,这是Java Web服务代码:

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("/putMethodTest")
    @PUT
    @Consumes(MediaType.TEXT_PLAIN)
    public Response putMethodTest(String requestString) {
        JSONObject requestJSON = new JSONObject(requestString);
        String deviceId = requestJSON.getString("deviceId");
        String mobileDeviceId = requestJSON.getString("mobileDeviceId");
        String deviceType = requestJSON.getString("deviceType");
        JSONObject response = new JSONObject();
        response.put("deviceId", deviceId);
        response.put("mobileDeviceId", mobileDeviceId);
        response.put("deviceType", deviceType);
        return Response.ok().entity(response.toString()).build();
    }

答案 1 :(得分:0)

像这样定义put函数:

//
// Put request
//
static func put(path: String, accessToken: Bool, data: Dictionary<String, AnyObject>, finish: (accessTokenX:String, data: JSON) -> ()) {
    apiRequest("PUT", path: path, accessToken: accessToken, contentType: nil, data: data) { (accessTokenX:String, data: AnyObject) in
        dispatch_async(dispatch_get_main_queue(), {
            finish(accessTokenX:accessTokenX, data: JSON(data))
        })
    }
}

使用示例:

    //
    // Update informations of the profile
    //
    static func accountUpdate(profile: [String: AnyObject], finish: (accessTokenX:String, data: JSON) -> ()) {
        let dataProfile = ["profile": profile]
        API.put("/users/profile", accessToken: true, data: dataProfile) { accessTokenX, data in finish(accessTokenX:accessTokenX, data: data)
        }
    }

答案 2 :(得分:-2)

试试这个!!!

http://jamesonquave.com/blog/making-a-post-request-in-swift/

func data_request()
{
    let url:NSURL = NSURL(string: url_to_request)!
    let session = NSURLSession.sharedSession()

    let request = NSMutableURLRequest(URL: url)
    request.HTTPMethod = "POST"
    request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData

    let paramString = "data=Hello"
    request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)

    let task = session.dataTaskWithRequest(request) {
    (
        let data, let response, let error) in

        guard let _:NSData = data, let _:NSURLResponse = response  where error == nil else {
            print("error")
            return
        }

        let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print(dataString)

    }

    task.resume()

}