2017-05-12 6 views
1

httpを介して投稿データをサーバーに送信しようとすると、投稿データは返されません。スウィフトhttpポストに投稿データがありません

var request = URLRequest(url: URL(string: "http://posttestserver.com/post.php")!) 
request.httpMethod = "POST" 
request.addValue("application/json", forHTTPHeaderField: "Content-Type") 
let json = "{\"key\":\"c7cbdc09820372\",\"rand\": \"13baa5274c2b107727\"}" 
request.httpBody = json.data(using: .utf8) 
URLSession.shared.dataTask(with: request) { (data, response, error) in 
     if data != nil, let result = String(data: data!, encoding: .utf8) { 
      print("\(result)") 
     } 
}.resume() 

結果は次のとおりです:

が正常に0ポスト変数をダンプ...ノーポスト本体、ここでのサンプルコードです。

+0

は、使用してみましたことを忘れてはいけませんAlamoFire?これはずっと簡単です。 –

+0

ありがとう、私は解決策を理解できない場合は、私はそれを使用することがあります。 – david72

答えて

0

このコードは、誰もが必要な場合には、動作します:

var request = URLRequest(url: URL(string: "http://posttestserver.com/post.php")!) 
request.httpMethod = "POST" 
let data = "key=c7cbdc09820372&rand=13baa5274c2b107727" 
request.httpBody = json.data(using: .utf8) 
URLSession.shared.dataTask(with: request) { (data, response, error) in 
    if data != nil, let result = String(data: data!, encoding: .utf8) { 
     print("\(result)") 
    } 
}.resume() 

は与える:

2つのポスト変数を正常にダンプしました....

0

あなたのJSON文字列が辞書に変換してから

jsonData =みては? JSONSerialization.data(withJSONObject:辞書、オプション:.prettyPrinted)

request.httpBody = jsonData

+0

ありがとうございますが、これは役に立たない – david72

0

HTTP POST /取得要求 のparams =「のparam1 =値& PARAM2 = value2の」 のための最高の機能を使用すると、JSONを使用したい場合は、Content-Typeの値に変更する必要がありますが

public func HttpPost(params:String, completion: @escaping (_ success: Bool, _ object: NSDictionary?) ->()) { 
      let configuration = URLSessionConfiguration.default 
      let session = URLSession(configuration: configuration) 
      let url = NSURL(string: /* here post url */) 
      var request = URLRequest(url: url! as URL) 
      request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") 
      request.httpMethod = "POST" 
      request.httpBody = params.data(using: String.Encoding.utf8)! 
      let task = session.dataTask(with: request) { 
       data, response, error in 
       if let httpResponse = response as? HTTPURLResponse { 
        let json = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) 
        if json == nil { 
         completion(false, nil) 
        } 
        else{ 
         completion(true, json as! NSDictionary?) 
        } 
       } 
       if (error != nil) { 
        completion(false, nil) 
       } 
      } 
      task.resume() 
     } 
関連する問題