[問題] c#登入api

看板C_Sharp作者 (談無慾)時間7年前 (2016/10/18 18:58), 7年前編輯推噓0(0012)
留言12則, 3人參與, 最新討論串1/2 (看更多)
大家好 最近剛要學call web api 以下是我的疑問 post使用的是64base Encode 送出 回傳的值是json https://gist.github.com/Aix-Shiao/bf7df4258cfb935fca06bafde3c14551 以上是我的code string postData = "myjson"; myjson 是我將 {"account":"ooo@xxx.com.tw", "password":"pass1234"} 這串json 丟入 https://www.base64encode.org/ 這個網址產生出來的 ======================= 我想問說 sting postDate -> byte[] postDataBytes -> Convert.ToBase64String(postDataBytes)-> Convert.FromBase64String(returnValue); 不知道這樣的轉換邏輯是否有問題? 錯誤代碼一直是無post資料 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 59.124.46.82 ※ 文章網址: https://www.ptt.cc/bbs/C_Sharp/M.1476788293.A.59C.html ※ 編輯: MOONY135 (59.124.46.82), 10/18/2016 18:59:25

10/18 20:58, , 1F
當然有問題,ToBase64String再FromBase64String不就轉過去
10/18 20:58, 1F

10/18 20:58, , 2F
再轉回來變成什麼都沒做
10/18 20:58, 2F

10/18 21:02, , 3F
應該是把base64 string再轉成byte(ASCII或UTF8都可)
10/18 21:02, 3F
byte[] postDataBytes = Encoding.UTF8.GetBytes(postData); string returnValue = Convert.ToBase64String(postDataBytes); byte[] ans = Encoding.UTF8.GetBytes(returnValue); req.Method = "POST"; req.ContentLength = ans.Length; Stream requestStream = req.GetRequestStream(); requestStream.Write(ans, 0, ans.Length); HttpWebResponse response = (HttpWebResponse)req.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream()); string returnString = reader.ReadToEnd(); response.Close();

10/18 21:03, , 4F
或requeststream再包StreamWriter直接傳入base64 string
10/18 21:03, 4F

10/18 21:13, , 5F
另外跟你的問題沒關係,純粹好奇為什麼response能回json
10/18 21:13, 5F

10/18 21:15, , 6F
request要把json多轉一次base64? 設計這API是...
10/18 21:15, 6F
目前這樣改還是回傳錯誤指令 NOT POST.... 卡一整天了 腦袋變得很笨

10/18 22:07, , 7F
這樣是base64編碼過的utf8編碼的json資料這點是沒問題的
10/18 22:07, 7F

10/18 22:08, , 8F
但是你打的web api的規格是不是這樣,或是有沒有錯在別的地
10/18 22:08, 8F

10/18 22:09, , 9F
方就不能保證了
10/18 22:09, 9F

10/18 23:26, , 10F
你確定web api沒錯?先用postman或fiddler之類的丟丟看吧
10/18 23:26, 10F
WEB API沒錯 POSTMAN用過了 我知道錯在哪邊了 string returnValue = Convert.ToBase64String(postDataBytes); byte[] ans = Encoding.UTF8.GetBytes(returnValue); 這邊多轉一次是腦殘了 string postData = <-這一段其實我早用網頁版的轉成64BASE了 接下來只要轉乘BYTE 就可以丟進REQUEST了 ※ 編輯: MOONY135 (114.25.242.194), 10/19/2016 00:11:37

10/19 09:09, , 11F
我覺得你的問題不是在用程式多轉一次,是先用手動轉...
10/19 09:09, 11F

10/19 09:40, , 12F
哈 自作孽
10/19 09:40, 12F
文章代碼(AID): #1O1W15MS (C_Sharp)
討論串 (同標題文章)
文章代碼(AID): #1O1W15MS (C_Sharp)