Swift Alamofire HTTP获取请求

时间:2018-07-18 16:32:41

标签: ios swift alamofire

请求代码:

static func testRequest() {
        Alamofire.request(Constants.baseURL,
                          method: .get,
                          parameters: ["data": "contentperson son"]).response { response in
            print("Request: \(response.request)")
            print("Response: \(response.response)")
            print("Error: \(response.error)")

            if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
                print("Data: \(utf8Text)")
            }
        }
    }

来源:Github ReadMe for Alamofire

我遇到了麻烦。该请求应使用data: contentperson son作为请求正文,但事实并非如此。我没有返回JSON对象。服务器已100%建立连接,但似乎无法理解我的要求。发送此请求的python程序不会返回信息。

请求返回:

Request: Optional(URL?data=contentperson%20son)
Response: Optional(<NSHTTPURLResponse: 0x600000833dc0> { URL: URL?data=contentperson%20son } { Status Code: 200, Headers {
    Connection =     (
        "keep-alive"
    );
    "Content-Encoding" =     (
        gzip
    );
    "Content-Type" =     (
        "text/html; charset=utf-8"
    );
    Date =     (
        "Wed, 18 Jul 2018 16:58:48 GMT"
    );
    Server =     (
        "nginx/1.10.3 (Ubuntu)"
    );
    "Transfer-Encoding" =     (
        Identity
    );
    "X-Frame-Options" =     (
        SAMEORIGIN
    );
} })
Error: nil
Data: The request data is empty.

它正在通过请求功能连接到Django服务器:

def Hello(request):
if(request.method == "GET"):
    data = request.body
    decoded_data = data.decode("utf-8")
    if(decoded_data == ''):
        return HttpResponse("The request data is empty.")
    decoded_data = decoded_data.split(" ")
    #decoded_data[0] is the model type (contentmedia, contenttext, contentperson, contentsite), decoded_data[1] is keyword
    try:
        connected_database = sqlite3.connect('db.sqlite3')
        c = connected_database.cursor()
        c.execute("select * from dataentry_" + decoded_data[0] + " where title like ('%" + decoded_data[1] + "%')")
        connected_database.commit()
        results = c.fetchall()
    except:
        return HttpResponse("Error in reading the database.")
    return HttpResponse(str(results))

2 个答案:

答案 0 :(得分:1)

我不使用Alamofire,但是我认为swift脚本可以正常工作。要通过直接请求进行某些测试,例如:

    let url = "http://...?..."
    if let myUrl = URL(string: url)
    {
        URLSession.shared.dataTask(with: myUrl)
        {
            (data, response, err) in

            if let data = data
            {
                let dataString = String(data: data, encoding: .utf8)
                ...
            }
        }.resume()
    }

就像Lame所说的那样,GET请求只是一个包含查询(?...)的URL。 存在HttpBody时使用POST请求。常见的用途是发送敏感信息,例如密码,通常像GET查询一样发送参数(例如x = 23&y = 45&z = elephant ...)

所以我想DJANGO逻辑有问题。另外,我也不熟悉,但是request.body对于GET请求似乎是错误的。 (不过,测试在POST请求中是否不存在是正确的)。我猜你想解析查询...

答案 1 :(得分:0)

Try this ...

Alamofire.request(url)
                .responseJSON { (response:DataResponse<Any>) in
    switch(response.result) {
                    case .success(_):
                    break

                    case .failure(_):

                    break
                    }
}