Alamofire와 함께 본문에 단순 문자열이 포함된 POST 요청
내 iOS 앱에서 알라모파이어가 있는 HTTP 본문에 간단한 문자열로 POST 요청을 보내는 것이 어떻게 가능합니까?
기본적으로 Alamofire에는 요청에 대한 매개 변수가 필요합니다.
Alamofire.request(.POST, "http://mywebsite.example/post-request", parameters: ["foo": "bar"])
이러한 매개 변수에는 키-값-쌍이 포함됩니다.그러나 HTTP 본문에 키 값 문자열이 있는 요청을 보내고 싶지 않습니다.
제 말은 이런 것입니다.
Alamofire.request(.POST, "http://mywebsite.example/post-request", body: "myBodyString")
당신의 예Alamofire.request(.POST, "http://mywebsite.example/post-request", parameters: ["foo": "bar"])이미 "foo=bar" 문자열을 본문으로 포함하고 있습니다.하지만 만약 당신이 정말로 커스텀 포맷의 문자열을 원한다면요.다음을 수행할 수 있습니다.
Alamofire.request(.POST, "http://mywebsite.example/post-request", parameters: [:], encoding: .Custom({
(convertible, params) in
var mutableRequest = convertible.URLRequest.copy() as NSMutableURLRequest
mutableRequest.HTTPBody = "myBodyString".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
return (mutableRequest, nil)
}))
참고:parameters해서는 안 됩니다nil
업데이트(Alamofire 4.0, Swift 3.0):
Alamofire 4.0에서는 API가 변경되었습니다.따라서 맞춤형 인코딩을 위해서는 다음과 같은 값/객체가 필요합니다.ParameterEncoding의전
extension String: ParameterEncoding {
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var request = try urlRequest.asURLRequest()
request.httpBody = data(using: .utf8, allowLossyConversion: false)
return request
}
}
Alamofire.request("http://mywebsite.example/post-request", method: .post, parameters: [:], encoding: "myBody", headers: [:])
다음을 수행할 수 있습니다.
- Alamofire 개체를 별도로 요청했습니다.
- 문자열을 데이터로 변환
httpBody에 데이터 입력
var request = URLRequest(url: URL(string: url)!) request.httpMethod = HTTPMethod.post.rawValue request.setValue("application/json", forHTTPHeaderField: "Content-Type") let pjson = attendences.toJSONString(prettyPrint: false) let data = (pjson?.data(using: .utf8))! as Data request.httpBody = data Alamofire.request(request).responseJSON { (response) in print(response) }
알라모파이어를 사용하면 설정하기에 충분합니다.encoding에 타자를 치다.URLEncoding.httpBody
그러면 코드에서 json으로 정의한 데이터를 http 본문의 문자열로 보낼 수 있습니다.
제게 효과가 있었습니다.
Badr Filali의 질문에 대해 업데이트됨:
var url = "http://..."
let _headers : HTTPHeaders = ["Content-Type":"application/x-www-form-urlencoded"]
let params : Parameters = ["grant_type":"password","username":"mail","password":"pass"]
let url = NSURL(string:"url" as String)
request(url, method: .post, parameters: params, encoding: URLEncoding.httpBody, headers: _headers).responseJSON(
completionHandler: { response in response
let jsonResponse = response.result.value as! NSDictionary
if jsonResponse["access_token"] != nil
{
access_token = String(describing: jsonResponse["accesstoken"]!)
}
})
알라모파이어의 매니저를 연장하기 위해 @Silmaril의 답변을 수정했습니다.이 솔루션은 EVReflection을 사용하여 개체를 직접 직렬화합니다.
//Extend Alamofire so it can do POSTs with a JSON body from passed object
extension Alamofire.Manager {
public class func request(
method: Alamofire.Method,
_ URLString: URLStringConvertible,
bodyObject: EVObject)
-> Request
{
return Manager.sharedInstance.request(
method,
URLString,
parameters: [:],
encoding: .Custom({ (convertible, params) in
let mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest
mutableRequest.HTTPBody = bodyObject.toJsonString().dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
return (mutableRequest, nil)
})
)
}
}
그런 다음 다음과 같이 사용할 수 있습니다.
Alamofire.Manager.request(.POST, endpointUrlString, bodyObject: myObjectToPost)
일리야 크리트의 대답을 바탕으로
세부 사항
- Xcode 버전 10.2.1(10E1001)
- 스위프트 5
- 알라모파이어 4.8.2
해결책
import Alamofire
struct BodyStringEncoding: ParameterEncoding {
private let body: String
init(body: String) { self.body = body }
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
guard var urlRequest = urlRequest.urlRequest else { throw Errors.emptyURLRequest }
guard let data = body.data(using: .utf8) else { throw Errors.encodingProblem }
urlRequest.httpBody = data
return urlRequest
}
}
extension BodyStringEncoding {
enum Errors: Error {
case emptyURLRequest
case encodingProblem
}
}
extension BodyStringEncoding.Errors: LocalizedError {
var errorDescription: String? {
switch self {
case .emptyURLRequest: return "Empty url request"
case .encodingProblem: return "Encoding problem"
}
}
}
사용.
Alamofire.request(url, method: .post, parameters: nil, encoding: BodyStringEncoding(body: text), headers: headers).responseJSON { response in
print(response)
}
요청에서 문자열을 원시 본문으로 게시하려는 경우
return Alamofire.request(.POST, "http://mywebsite.com/post-request" , parameters: [:], encoding: .Custom({
(convertible, params) in
let mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest
let data = ("myBodyString" as NSString).dataUsingEncoding(NSUTF8StringEncoding)
mutableRequest.HTTPBody = data
return (mutableRequest, nil)
}))
저는 문자열 배열을 위해 그것을 해왔습니다.이 솔루션은 본문의 문자열에 맞게 조정됩니다.
알라모파이어 4의 "원주민" 방식:
struct JSONStringArrayEncoding: ParameterEncoding {
private let myString: String
init(string: String) {
self.myString = string
}
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = urlRequest.urlRequest
let data = myString.data(using: .utf8)!
if urlRequest?.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest?.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
urlRequest?.httpBody = data
return urlRequest!
}
}
그런 다음 다음과 같이 요청합니다.
Alamofire.request("your url string", method: .post, parameters: [:], encoding: JSONStringArrayEncoding.init(string: "My string for body"), headers: [:])
저는 @afrodev의 답변을 참조로 사용했습니다.제 경우에는 요청 시 게시해야 하는 문자열로 제 기능에 대한 매개 변수를 가져갑니다.코드는 다음과 같습니다.
func defineOriginalLanguage(ofText: String) {
let text = ofText
let stringURL = basicURL + "identify?version=2018-05-01"
let url = URL(string: stringURL)
var request = URLRequest(url: url!)
request.httpMethod = HTTPMethod.post.rawValue
request.setValue("text/plain", forHTTPHeaderField: "Content-Type")
request.httpBody = text.data(using: .utf8)
Alamofire.request(request)
.responseJSON { response in
print(response)
}
}
let parameters = ["foo": "bar"]
// All three of these calls are equivalent
AF.request("https://httpbin.org/post", method: .post, parameters: parameters)
AF.request("https://httpbin.org/post", method: .post, parameters: parameters, encoder: URLEncodedFormParameterEncoder.default)
AF.request("https://httpbin.org/post", method: .post, parameters: parameters, encoder: URLEncodedFormParameterEncoder(destination: .httpBody))
func paramsFromJSON(json: String) -> [String : AnyObject]?
{
let objectData: NSData = (json.dataUsingEncoding(NSUTF8StringEncoding))!
var jsonDict: [ String : AnyObject]!
do {
jsonDict = try NSJSONSerialization.JSONObjectWithData(objectData, options: .MutableContainers) as! [ String : AnyObject]
return jsonDict
} catch {
print("JSON serialization failed: \(error)")
return nil
}
}
let json = Mapper().toJSONString(loginJSON, prettyPrint: false)
Alamofire.request(.POST, url + "/login", parameters: paramsFromJSON(json!), encoding: .JSON)
제 경우, 내용 유형: "content-Type": "application/x-www-form-urlenced"로 라모파이어 게시 요청의 인코딩을 변경해야 했습니다.
출처 : JSONENCODING.기본값: URLencoding.httpBody
여기:
let url = ServicesURls.register_token()
let body = [
"UserName": "Minus28",
"grant_type": "password",
"Password": "1a29fcd1-2adb-4eaa-9abf-b86607f87085",
"DeviceNumber": "e9c156d2ab5421e5",
"AppNotificationKey": "test-test-test",
"RegistrationEmail": email,
"RegistrationPassword": password,
"RegistrationType": 2
] as [String : Any]
Alamofire.request(url, method: .post, parameters: body, encoding: URLEncoding.httpBody , headers: setUpHeaders()).log().responseJSON { (response) in
Xcode 8.X, Swift 3.X
간편한 사용;
let params:NSMutableDictionary? = ["foo": "bar"];
let ulr = NSURL(string:"http://mywebsite.com/post-request" as String)
let request = NSMutableURLRequest(url: ulr! as URL)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let data = try! JSONSerialization.data(withJSONObject: params!, options: JSONSerialization.WritingOptions.prettyPrinted)
let json = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
if let json = json {
print(json)
}
request.httpBody = json!.data(using: String.Encoding.utf8.rawValue);
Alamofire.request(request as! URLRequestConvertible)
.responseJSON { response in
// do whatever you want here
print(response.request)
print(response.response)
print(response.data)
print(response.result)
}
언급URL : https://stackoverflow.com/questions/27855319/post-request-with-a-simple-string-in-body-with-alamofire
'programing' 카테고리의 다른 글
| org.springframework.mail.javamail을 자동으로 배선할 수 없습니다.JavaMailSender (0) | 2023.08.11 |
|---|---|
| ARG 또는 ENV, 이 경우 어떤 것을 사용해야 합니까? (0) | 2023.08.11 |
| 안드로이드 개발용 MS Visual Studio를 어떻게 사용할 수 있습니까? (0) | 2023.08.11 |
| 'Install-Module' 용어가 cmdlet의 이름으로 인식되지 않습니다. (0) | 2023.08.11 |
| &operator를 사용하여 PowerShell에서 MSBuild를 호출하는 방법은 무엇입니까? (0) | 2023.08.06 |