gpt4 book ai didi

ios - 无法读取数据,因为它的格式不正确 - HTTP 网络

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:12:50 24 4
gpt4 key购买 nike

代码

    let session = URLSession.shared

// prepare json data
let json: [String: Any] = ["email": "test_mobile@mysite.com"]

let jsonData = try? JSONSerialization.data(withJSONObject: json)

let proceedURL = NSURL(string:"https://mysitename.herokuapp.com/api/users/isUser")
//let proceedURL = NSURL(string:"https://google.com")
let request = NSMutableURLRequest(url: proceedURL! as URL)
//HTTP Headers
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/www.inception.v1", forHTTPHeaderField: "Accept")
request.addValue("Authorization", forHTTPHeaderField: "Basic aW5jZXB0aW9uQGZ1cmRvOmljM=")
request.httpMethod = "POST"
//request.httpBody = jsonData


// insert json data to the request
request.httpBody = jsonData

//create dataTask using the session object to send data to the server
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in

guard error == nil else {
return
}

guard let data = data else {
return
}

// Print out response string
let responseString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
print("responseString = \(responseString!)")

do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: AnyObject] {
print(json)
// handle json...
}

} catch let error {
print("error : " + error.localizedDescription)
}

})

task.resume()

错误:无法读取数据,因为它的格式不正确。

我是 iphone 应用程序开发的初学者,请帮助我并为建立网络连接提供更好的建议(就像在 android 中我正在使用 Volley 库)

实际响应是:

{
"status": 1,
"http_status_code": 200,
"data": {
"email": "test_mobile@mysite.com",
"phone": "8090909000"
}
}

我在 Android 上使用相同的东西并在 postman 中进行测试。

// Print out response string
let responseString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)

对于上层代码响应什么都没有

最佳答案

使用 Alamofire。

let json: [String: Any] = ["email": "test_mobile@mysite.com"]

Alamofire.request(.POST, "https://mysitename.herokuapp.com/api/users/isUser" , parameters: json, encoding: .JSON).responseJSON {
Response in
switch Response.result {
case .Success(let _data):
let JsonData = JSON(_data)
print("JsonData : \(JsonData)")


//handle json


case .Failure(let _error):
print(_error)
let AlertBox = UIAlertController(title: "Connection Failed", message: "No Connection", preferredStyle: .Alert)
let ActionBox = UIAlertAction(title: "Ok" , style: .Default, handler: { _ in})
AlertBox.addAction(ActionBox)
self.presentViewController(AlertBox, animated: true, completion: nil)
}

关于ios - 无法读取数据,因为它的格式不正确 - HTTP 网络,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42997965/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com