質問するログイン新規登録

質問編集履歴

1

追記

2019/06/24 09:36

投稿

hodoru3sei
hodoru3sei

スコア284

title CHANGED
File without changes
body CHANGED
@@ -66,4 +66,49 @@
66
66
  } })
67
67
  ```
68
68
 
69
- APIにPOSTを行った経験がないので何が悪いのか検討がつかず困っています。何が間違っているのでしょうか?
69
+ APIにPOSTを行った経験がないので何が悪いのか検討がつかず困っています。何が間違っているのでしょうか?
70
+
71
+
72
+
73
+ #### 追記
74
+ [公式ドキュメント](https://developer.apple.com/documentation/foundation/url_loading_system/uploading_data_to_a_website)を読んで以下の様なコードに書き換えてみたのですがserver errorの部分に入ってしまいます。
75
+ ```Swift
76
+ override func viewDidLoad() {
77
+ super.viewDidLoad()
78
+ let url = URL(string: "https://labs.goo.ne.jp/api/hiragana")
79
+ var request = URLRequest(url: url!)
80
+ request.httpMethod = "POST"
81
+
82
+ request.addValue("application/json", forHTTPHeaderField: "Content-Type")
83
+ request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
84
+
85
+ let postData = PostData(app_id: "作成したapp_id", request_id: "", sentence: "焼き芋", output_type: "hiragana")
86
+
87
+
88
+ guard let uploadData = try? JSONEncoder().encode(postData) else {
89
+ return
90
+ }
91
+ request.httpBody = uploadData
92
+
93
+ let task = URLSession.shared.uploadTask(with: request, from: uploadData) { data, response, error in
94
+ if let error = error {
95
+ print ("error: (error)")
96
+ return
97
+ }
98
+
99
+ guard let response = response as? HTTPURLResponse,
100
+ (200...299).contains(response.statusCode) else {
101
+ print ("server error")
102
+ return
103
+ }
104
+ if let mimeType = response.mimeType,
105
+ mimeType == "application/json",
106
+ let data = data,
107
+ let dataString = String(data: data, encoding: .utf8) {
108
+ print ("got data: (dataString)")
109
+ }
110
+ }
111
+ task.resume()
112
+ }
113
+ }
114
+ ```