gpt4 book ai didi

ios - 将 curl 命令转换为 iOS

转载 作者:搜寻专家 更新时间:2023-10-31 23:03:17 26 4
gpt4 key购买 nike

以下 curl 有效

curl -G -H "api_key: MYAPIKEY" https://api.semantics3.com/test/v1/products -d 'q={"upc":"70411576937"}'

但是,在尝试将其转换为 iOS 时出现以下错误:

Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." {NSErrorFailingURLStringKey=https://api.semantics3.com/test/v1/products,...}

我在下面附上了我的代码,但我认为我的问题是在提交到 URL 的 json 数据之前的“q=”。如果是这样,这叫什么以及如何在我的 json 数据之前放置“q=”?不过,由于 iOS 始终如一地向我们提供不相关的错误消息,我无法准确判断。谢谢。

    var urlString = "https://api.semantics3.com/test/v1/products"
var request = NSMutableURLRequest(URL: NSURL(string: urlString)!)
var response: NSURLResponse?
var error: NSErrorPointer = nil
var reqText = ["upc": "70411576937"]
var err: NSError?

request.HTTPBody = NSJSONSerialization.dataWithJSONObject(reqText, options: nil, error: &err)
request.HTTPMethod = "GET"
request.addValue("MYAPIKEY", forHTTPHeaderField: "api_key")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var session = NSURLSession.sharedSession()

var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
if(err != nil) {
println(err!.localizedDescription)
}
else {
//this is where the error is printed
println(error)
var parseError : NSError?
// parse data
let unparsedArray: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: &parseError)
println(parseError)
if let resp = unparsedArray as? NSDictionary {
println(resp)
}
}
})
task.resume()

最佳答案

正文不用于 GET http 方法。使用以下代码连接您的参数:

extension String {

/// Percent escape value to be added to a URL query value as specified in RFC 3986
///
/// This percent-escapes all characters besize the alphanumeric character set and "-", ".", "_", and "~".
///
/// http://www.ietf.org/rfc/rfc3986.txt
///
/// :returns: Return precent escaped string.

func stringByAddingPercentEncodingForURLQueryValue() -> String? {
let characterSet = NSMutableCharacterSet.alphanumericCharacterSet()
characterSet.addCharactersInString("-._~")

return self.stringByAddingPercentEncodingWithAllowedCharacters(characterSet)
}

}

extension Dictionary {

/// Build string representation of HTTP parameter dictionary of keys and objects
///
/// This percent escapes in compliance with RFC 3986
///
/// http://www.ietf.org/rfc/rfc3986.txt
///
/// :returns: String representation in the form of key1=value1&key2=value2 where the keys and values are percent escaped

func stringFromHttpParameters() -> String {
let parameterArray = map(self) { (key, value) -> String in
let percentEscapedKey = (key as! String).stringByAddingPercentEncodingForURLQueryValue()!
let percentEscapedValue = (value as! String).stringByAddingPercentEncodingForURLQueryValue()!
return "\(percentEscapedKey)=\(percentEscapedValue)"
}

return join("&", parameterArray)
}

}


var urlString = "https://api.semantics3.com/test/v1/products"
var reqText = ["upc": "70411576937"]
var err: NSError?

let parameterString = reqText.stringFromHttpParameters()
let requestURL = NSURL(string:"\(urlString)?\(parameterString)")!

var request = NSMutableURLRequest(URL: NSURL(string: urlString)!)
var response: NSURLResponse?
var error: NSError?

request.HTTPMethod = "GET"
request.addValue("MYAPIKEY", forHTTPHeaderField: "api_key")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var session = NSURLSession.sharedSession()

部分编辑:SWIFT 2.1(更新)

extension Dictionary {

func stringFromHttpParameters() -> String {
let parameterArray = self.map { (key, value) -> String in
let percentEscapedKey = (key as! String).stringByAddingPercentEncodingForURLQueryValue()!
let percentEscapedValue = (value as! String).stringByAddingPercentEncodingForURLQueryValue()!
return "\(percentEscapedKey)=\(percentEscapedValue)"
}

return parameterArray.joinWithSeparator("&")
}

}

关于ios - 将 curl 命令转换为 iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30720714/

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