static void Main(string[] args) { String TestStr = "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"; Dictionary <string, string> HeadPostParam = new Dictionary <string, string>(); HeadPostParam.Add("version", "4.0.0.1"); HeadPostParam.Add("member_id", "100000178"); //商户号 HeadPostParam.Add("client_ip", "116.236.217.150"); //要与服务器IP保持一致 HeadPostParam.Add("file_type", "fi"); //收款:fi 出款:fo HeadPostParam.Add("settle_date", "2016-11-02"); //指定日期的对帐文件(除当天) String RequestUrl = "https://vgw.baofoo.com/boas/api/fileLoadNewRequest"; //测试请求地址 String PostString = HttpsRequest.GetParamsStr(HeadPostParam); Console.WriteLine("请求参数:" + RequestUrl + "?" + PostString); String ReturnStr = HttpsRequest.OpenReadWithHttps(RequestUrl, PostString); Console.WriteLine("返回结果:" + ReturnStr); if (String.IsNullOrEmpty(ReturnStr)) { Console.WriteLine("请求返回异常!"); Console.ReadKey(); return; } int sTRoF = ReturnStr.IndexOf("resp_code=0000"); if (sTRoF < 0) { Console.WriteLine("下载失败!"); Console.ReadKey(); return; } String[] Splitstr = Regex.Split(ReturnStr, "resp_body=", RegexOptions.IgnoreCase); //解板返回的文件参数 byte[] String64 = Base64.Decode(Splitstr[1]); //Base64编码 字符编码UF8 try { String fileName = "d:/" + DateTime.Now.ToString("yyyy-MM-ddHHmmss") + "_" + HeadPostParam["file_type"] + ".zip"; //存在本地的路径(自行设置) FileStream fs = new FileStream(fileName, FileMode.Create); fs.Write(String64, 0, String64.Length); fs.Close(); Console.Write("文件下载成功!路径:" + fileName); } catch (Exception e) { Console.WriteLine("写入文件失败!"); Console.Write(e.Message); Console.ReadKey(); } Console.ReadKey(); }
/// <summary> /// Создать HTTP запрос /// </summary> /// <param name="methodName"> /// SOAP-метод /// </param> /// <returns> /// HTTP запрос /// </returns> private HttpsRequest CreateRequest(string methodName) { var request = new HttpsRequest(); request.Head.AppendFormat("SOAPAction: {0}\r\n", string.Join("/", uri, methodName)); request.Head.Append("Accept-Encoding: gzip, deflate\r\n"); request.Head.AppendFormat("Host: {0}\r\n", uri.Host); return(request); }
public void DeleteSet(long setID, Action success, Action <Exception> errorHandler, CancellationToken token) { var req = new HttpsRequest("DELETE", string.Format(CultureInfo.InvariantCulture, "/2.0/sets/{0}", setID)); AuthorizeRequest(req, true); FetchJSON( req, _ => success(), errorHandler, token); }
public void SetStarred(long setID, bool starred, Action success, Action <Exception> errorHandler, CancellationToken token) { if (Credentials == null) { throw new InvalidOperationException("Must be logged in to mark or unmark a group as favourite"); } var req = new HttpsRequest(starred ? "PUT" : "DELETE", "/2.0/users/" + Credentials.UserName + "/favorites/" + setID.ToString(CultureInfo.InvariantCulture)); AuthorizeRequest(req, true); FetchJSON( req, _ => success(), // No content is returned (HTTP 204) errorHandler, token); }
public void FetchSets(IEnumerable <long> ids, Action <List <SetInfo> > completion, Action <Exception> errorHandler, CancellationToken token) { var req = new HttpsRequest("GET", "/2.0/sets?set_ids=" + string.Join(",", from id in ids select id.ToString(CultureInfo.InvariantCulture))); AuthorizeRequest(req, false); FetchJSON( req, json => { try { completion(new JsonContext().FromJson <List <SetInfo> >(json)); } catch (JsonConvertException e) { errorHandler(e); } }, errorHandler, token); }
public void FetchSet(long id, Action <SetInfo> completion, Action <Exception> errorHandler, CancellationToken token) { var req = new HttpsRequest("GET", "/2.0/sets/" + id.ToString(CultureInfo.InvariantCulture)); AuthorizeRequest(req, false); FetchJSON( req, json => { try { completion(new JsonContext().FromJson <SetInfo>(json)); } catch (JsonConvertException e) { errorHandler(e); } }, errorHandler, token); }
public void FetchUserFavourites(string userName, Action <List <SetInfo> > completion, Action <Exception> errorHandler, CancellationToken token) { var req = new HttpsRequest("GET", "/2.0/users/" + Uri.EscapeUriString(userName) + "/favorites"); AuthorizeRequest(req, true); FetchJSON( req, json => { try { var sets = new JsonContext().FromJson <List <SetInfo> >(json); completion(sets); } catch (JsonConvertException e) { errorHandler(e); } }, errorHandler, token); }
public void FetchUserData(string userName, Action <UserInfo> completion, Action <Exception> errorHandler, CancellationToken token) { var req = new HttpsRequest("GET", "/2.0/users/" + Uri.EscapeUriString(userName)); AuthorizeRequest(req, false); FetchJSON( req, json => { try { completion(new JsonContext().FromJson <UserInfo>(json)); } catch (JsonConvertException e) { errorHandler(e); } }, errorHandler, token); }
public void SearchSets(string query, bool searchTerms, Action <List <SetInfo> > completion, Action <Exception> errorHandler, CancellationToken token) { var req = new HttpsRequest("GET", "/2.0/search/sets?sort=most_studied&" + (searchTerms ? "term=" : "q=") + Uri.EscapeDataString(query)); AuthorizeRequest(req, false); FetchJSON( req, json => { try { var sets = new JsonContext().FromJson <List <SetInfo> >(((JsonDictionary)json).Items["sets"]); completion(sets); } catch (JsonConvertException e) { errorHandler(e); } }, errorHandler, token); }
public void EditSet(SetInfo si, string newPassword, string newVisibility, string newPermissions, IEnumerable <long> groupIDs, Action success, Action <Exception> errorHandler, CancellationToken token) { var req = new HttpsRequest("PUT", string.Format(CultureInfo.InvariantCulture, "/2.0/sets/{0}", si.ID)); var postData = new MemoryStream(); using (var writer = new StreamWriter(postData)) WriteSetInfo(si, writer, newPassword, newVisibility, newPermissions, groupIDs); req.ContentType = "application/x-www-form-urlencoded"; req.PostData = postData.ToArray(); AuthorizeRequest(req, true); FetchJSON( req, json => success(), errorHandler, token); }
public void SubmitPassword(long setID, string password, Action success, Action <Exception> failure, CancellationToken token) { var req = new HttpsRequest("POST", string.Format(CultureInfo.InvariantCulture, "/2.0/sets/{0}/password", setID)); AuthorizeRequest(req, true); var postData = new MemoryStream(); using (var writer = new StreamWriter(postData)) WriteQueryString(writer, "password", password); req.ContentType = "application/x-www-form-urlencoded"; req.PostData = postData.ToArray(); FetchJSON( req, json => success(), failure, token); }
public void FetchUserGroups(string userName, Action <List <GroupInfo> > completion, Action <Exception> errorHandler, CancellationToken token) { var req = new HttpsRequest("GET", string.Format(CultureInfo.InvariantCulture, "/2.0/users/{0}/groups", Uri.EscapeUriString(userName))); AuthorizeRequest(req, false); FetchJSON( req, json => { try { var groups = new JsonContext { RelaxedNumericConversion = true }.FromJson <List <GroupInfo> >(json); completion(groups); } catch (JsonConvertException e) { errorHandler(e); } }, errorHandler, token); }
/// <summary> /// Takes an OAuth code and turns it into an API token. /// </summary> /// <param name="code">A code returned from the OAuth page (https://quizlet.com/authorize/)</param> /// <param name="success">A delegate to be called when the authentication succeeds.</param> /// <param name="failure">What to do when the authentication fails.</param> /// <param name="token">A CancellationToken, which is currently useless.</param> public void Authenticate(string code, Action success, Action <Exception> failure, CancellationToken token) { var fields = "grant_type=authorization_code&code=" + code + "&redirect_uri=https://q.asztal.net/"; var req = new HttpsRequest("POST", "/oauth/token"); req.BasicAuthorization(ClientID, SecretKey); req.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; req.PostData = Encoding.UTF8.GetBytes(fields); FetchJSON(req, json => { try { if (json is JsonDictionary) { var ctx = new JsonContext(); var accessToken = ctx.FromJson <string>((json as JsonDictionary).Items["access_token"]); var userName = ctx.FromJson <string>((json as JsonDictionary).Items["user_id"]); var tokenExpiry = DateTime.Now.AddSeconds(ctx.FromJson <double>((json as JsonDictionary).Items["expires_in"])); Credentials = new Credentials(accessToken, userName, tokenExpiry); success(); } else { failure(new FormatException("Quizlet server returned an invalid response.")); } } catch (KeyNotFoundException) { failure(new FormatException("Quizlet server returned an invalid response.")); } catch (JsonConvertException) { failure(new FormatException("Quizlet server returned an invalid response.")); } }, failure, token); }
void AuthorizeRequest(HttpsRequest request, bool needsToken) { if (Credentials != null) { request.Authorization = "Bearer " + Credentials.Token; } else { if (needsToken) { throw new QuizletException("A quizlet API endpoint was called which needs authentication"); } // TODO: check if GET or POST or PUT etc. char delim = '?'; if (request.Path.Contains("?")) { delim = '&'; } request.Path = request.Path + delim + "client_id=" + ClientID; } }
public void CreateSet(SetInfo si, string password, IEnumerable <long> groupIDs, Action <long, Uri> completion, Action <Exception> errorHandler, CancellationToken token) { var req = new HttpsRequest("POST", "/2.0/sets"); var postData = new MemoryStream(); using (var writer = new StreamWriter(postData)) WriteSetInfo(si, writer, password, si.Visibility, si.Editable, groupIDs); req.ContentType = "application/x-www-form-urlencoded"; req.PostData = postData.ToArray(); AuthorizeRequest(req, true); FetchJSON( req, json => { try { if (!(json is JsonDictionary)) { throw new JsonConvertException("Expected a JSON dictionary"); } var ctx = new JsonContext(); var dict = (json as JsonDictionary).Items; var uri = new Uri(ctx.FromJson <string>(dict["url"])); var id = ctx.FromJson <long>(dict["set_id"]); completion(id, uri); } catch (JsonConvertException err) { errorHandler(err); } catch (KeyNotFoundException err) { errorHandler(new QuizletException("Invalid response from server", err)); } }, errorHandler, token); }
protected void Page_Load(object sender, EventArgs e) { Log.LogWrite(""); String txn_sub_type = Request.Params["txn_sub_type"]; if (String.IsNullOrEmpty(txn_sub_type)) { Response.Write("参数【txn_sub_type】不能为空"); Response.End(); } String pay_code = Request.Params["pay_code"]; //银行卡编码 String acc_no = Request.Params["acc_no"]; //银行卡卡号 String id_card = Request.Params["id_card"]; //身份证号码 String id_holder = Request.Params["id_holder"]; //姓名 String mobile = Request.Params["mobile"]; //银行预留手机号 String next_txn_sub_type = Request.Params["next_txn_sub_type"]; //下一下进行的交易子类 String trans_id = Request.Params["trans_id"]; //商户订单号 Dictionary <String, String> HeadPostParam = new Dictionary <String, String>(); HeadPostParam.Add("version", "4.0.0.0"); HeadPostParam.Add("member_id", ConfigurationManager.AppSettings["MemberId"]); HeadPostParam.Add("terminal_id", ConfigurationManager.AppSettings["TerminalId"]); HeadPostParam.Add("txn_type", "0431"); HeadPostParam.Add("txn_sub_type", txn_sub_type); HeadPostParam.Add("data_type", ConfigurationManager.AppSettings["DataType"]); /** * 报文体 * ============================================= * */ Dictionary <String, Object> XMLArray = new Dictionary <String, Object>(); /** * * 公共参数 * */ XMLArray.Add("txn_sub_type", HeadPostParam["txn_sub_type"]); XMLArray.Add("biz_type", "0000"); XMLArray.Add("terminal_id", HeadPostParam["terminal_id"]); XMLArray.Add("member_id", HeadPostParam["member_id"]); XMLArray.Add("trans_serial_no", GetTSNID()); XMLArray.Add("trade_date", DateTime.Now.ToString("yyyyMMddHHmmss")); XMLArray.Add("additional_info", "附加信息"); XMLArray.Add("req_reserved", "保留"); if (txn_sub_type.Equals("11")) { Log.LogWrite("=============================【 (" + txn_sub_type + ")预绑卡类交易】======================================="); if (String.IsNullOrEmpty(trans_id)) { Response.Write("商户订单号不能为空【trans_id】"); Log.LogWrite("商户订单号不能为空【trans_id】"); return; } XMLArray.Add("acc_no", acc_no); //商户订单号 XMLArray.Add("trans_id", trans_id); //商户订单号 XMLArray.Add("id_card_type", "01"); //证件类型固定01(身份证) XMLArray.Add("id_card", id_card); XMLArray.Add("id_holder", id_holder); XMLArray.Add("mobile", mobile); XMLArray.Add("acc_pwd", ""); XMLArray.Add("valid_date", ""); XMLArray.Add("valid_no", ""); XMLArray.Add("pay_code", pay_code); } else if (txn_sub_type.Equals("12")) { Log.LogWrite("=============================【 (" + txn_sub_type + ")确认绑卡交易】======================================="); String sms_code = Request.Params["sms_code"];//短信验证码 if (String.IsNullOrEmpty(trans_id)) { Response.Write("商户订单号不能为空【trans_id】,注:需和预绑卡交易订单号一致"); Log.LogWrite("商户订单号不能为空【trans_id】,注:需和预绑卡交易订单号一致"); return; } if (String.IsNullOrEmpty(sms_code)) { Response.Write("短信验证码不能为空【sms_code】"); Log.LogWrite("短信验证码不能为空【sms_code】"); return; } XMLArray.Add("trans_id", trans_id); XMLArray.Add("sms_code", sms_code); } else if (txn_sub_type.Equals("02")) { Log.LogWrite("=============================【 (" + txn_sub_type + ")解除绑卡交易】======================================="); String bind_id = Request.Params["bind_id"];//获取绑定标识 XMLArray.Add("bind_id", bind_id); } else if (txn_sub_type.Equals("03")) { Log.LogWrite("=============================【 (" + txn_sub_type + ")查询绑定关系类交易】======================================="); XMLArray.Add("acc_no", acc_no);//卡号 } else if (txn_sub_type.Equals("15")) { Log.LogWrite("=============================【 (" + txn_sub_type + ")支付类预支付交易】======================================="); Dictionary <String, Object> ClientIp = new Dictionary <String, Object>(); ClientIp.Add("client_ip", "100.0.0.0"); String TxnAmt = Request.Params["txn_amt"]; //交易金额额 String bind_id = Request.Params["bind_id"]; //获取绑定标识 XMLArray.Add("bind_id", bind_id); XMLArray.Add("trans_id", GetTransId()); XMLArray.Add("txn_amt", decimal.Round((decimal.Parse(TxnAmt) * 100), 0).ToString());//金额以分为单位(整型数据)并把元转换成分 XMLArray.Add("risk_content", ClientIp); } else if (txn_sub_type.Equals("16")) { Log.LogWrite("=============================【 (" + txn_sub_type + ")支付类支付确认交易】======================================="); String sms_code = Request.Params["sms_code"]; //交易金额额 String business_no = Request.Params["business_no"]; //宝付业务流水号 if (String.IsNullOrEmpty(business_no)) { Response.Write("宝付业务流水号不能为空【business_no】"); Log.LogWrite("宝付业务流水号不能为空【business_no】"); return; } XMLArray.Add("sms_code", sms_code); XMLArray.Add("business_no", business_no); } else if (txn_sub_type.Equals("06")) { Log.LogWrite("=============================【 (" + txn_sub_type + ")订单查询接口】======================================="); String orig_trans_id = Request.Params["orig_trans_id"];//订单号 XMLArray.Add("orig_trans_id", orig_trans_id); } else { Response.Write("[next_txn_sub_type]参数错误!"); Response.End(); } String TempRSAStr = ToXMLJSON.ObjectToXmlJson(XMLArray, HeadPostParam["data_type"]);//JSON或XML由date_type确定 Log.LogWrite("【" + HeadPostParam["txn_sub_type"] + "序例化(" + HeadPostParam["data_type"] + "):】" + TempRSAStr); TempRSAStr = RSAUtil.EncryptRSAByPfx(TempRSAStr, HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["PfxPath"]), ConfigurationManager.AppSettings["PfxPwd"]); Log.LogWrite("【" + HeadPostParam["txn_sub_type"] + "报文加密:】" + TempRSAStr);//记录日志 HeadPostParam.Add("data_content", TempRSAStr); String PostParam = HttpsRequest.GetParam(HeadPostParam); Log.LogWrite("【" + HeadPostParam["txn_sub_type"] + "请求参数拼接:】" + PostParam); String HTTPReturn = HttpsRequest.OpenReadWithHttps(ConfigurationManager.AppSettings["RUrl"], PostParam); Log.LogWrite("【" + HeadPostParam["txn_sub_type"] + "返回报文:】" + HTTPReturn); TempRSAStr = RSAUtil.DecryptRSAByCer(HTTPReturn, Server.MapPath(ConfigurationManager.AppSettings["CerPath"])); if (String.IsNullOrEmpty(TempRSAStr)) { Log.LogWrite("【解密结果】:解密失败"); Response.Write("解密失败!{" + TempRSAStr + "}<br>"); Response.End(); } string JSONstring = ""; if (HeadPostParam["data_type"].Equals("xml")) { JSONstring = JXDConvert.XmlToJson(TempRSAStr); } else { JSONstring = TempRSAStr; } Log.LogWrite("【返回明文解密:】" + JSONstring); Dictionary <String, Object> DJSON = JXDConvert.JsonToDictionary(JSONstring); Dictionary <String, Object> DJSONS = DJSON; if (HeadPostParam["data_type"].Equals("xml")) { DJSON = (Dictionary <String, Object>)DJSON["result"]; } Log.LogWrite("【对象转换】:" + DJSON["resp_code"]); String ReturnStr = ""; if (DJSON["resp_code"].Equals("0000")) { //此处商户可写自已的处理程序 ReturnStr = "返回码:" + DJSON["resp_code"] + " 返回消息:" + DJSON["resp_msg"]; if (txn_sub_type.Equals("11")) { ReturnStr = ToXMLJSON.ObjectToXmlJson(DJSONS["result"], "JSON"); } else if (txn_sub_type.Equals("12") || txn_sub_type.Equals("03")) { ReturnStr += ", 绑定编码:" + DJSON["bind_id"]; } else if (txn_sub_type.Equals("15") || txn_sub_type.Equals("14")) { ReturnStr = ToXMLJSON.ObjectToXmlJson(DJSONS["result"], "JSON"); } else if (txn_sub_type.Equals("16") || txn_sub_type.Equals("06")) { String MoneyStr = "(分)"; if (txn_sub_type.Equals("06")) {//查询返回单位为元 MoneyStr = "(元)"; } ReturnStr += ", 成功金额:" + DJSON["succ_amt"] + MoneyStr + ", 商户订单号:" + DJSON["trans_id"]; } } else if (txn_sub_type.Equals("15") || txn_sub_type.Equals("11")) { ReturnStr = ToXMLJSON.ObjectToXmlJson(DJSONS["result"], "JSON"); } else { ReturnStr = "返回码:" + DJSON["resp_code"] + ", 返回消息:" + DJSON["resp_msg"]; } Response.Write(ReturnStr); Log.LogWrite("=============================【 (" + txn_sub_type + ")结束】======================================="); }
/// <summary> /// Создать HTTP запрос /// </summary> /// <param name="methodName"> /// SOAP-метод /// </param> /// <returns> /// HTTP запрос /// </returns> private HttpsRequest CreateRequest(string methodName) { var request = new HttpsRequest(); request.Head.AppendFormat("SOAPAction: {0}\r\n", string.Join("/", uri, methodName)); request.Head.Append("Accept-Encoding: gzip, deflate\r\n"); request.Head.AppendFormat("Host: {0}\r\n", uri.Host); return request; }
void FetchJSON(HttpsRequest request, Action <JsonValue> completion, Action <Exception> errorHandler, CancellationToken token) { var op = System.ComponentModel.AsyncOperationManager.CreateOperation(null); request.UserAgent = "FlashcardsWP7/0.1 (" + Environment.OSVersion + "; .NET " + Environment.Version + ")"; try { token.Register(delegate { throw new OperationCanceledException(); }); ThreadPool.QueueUserWorkItem( _ => { Exception error; try { var client = new HttpsClient(Host.Host, Host.Port, Configuration.VerifyCertificates); var response = client.MakeRequest(request); var text = response.DecodeTextBody(); if (response.StatusCode == 204) { op.PostOperationCompleted(delegate { completion(null); }, null); return; } var json = JsonValue.Parse(new StringReader(text)); if (response.StatusCode / 100 != 2) { var dict = (JsonDictionary)json; var errorCode = new JsonContext().FromJson <string>(dict.Items["error"]); var errorText = new JsonContext().FromJson <string>(dict.Items["error_description"]); if (errorCode != null && errorText != null) { // TODO: find error code for needing password if (errorCode == "invalid_access") { throw new AccessDeniedException(errorText); } if (errorCode == "item_not_found") { throw new ItemNotFoundException(errorText); } if (errorCode == "item_deleted") { throw new ItemDeletedException(errorText); } throw new QuizletException(errorText); } throw new QuizletException("The Quizlet request failed (HTTP error " + response.StatusCode.ToString(CultureInfo.InvariantCulture) + ")."); } op.PostOperationCompleted(delegate { completion(json); }, null); return; } catch (QuizletException e) { error = e; } catch (OperationCanceledException e) { error = e; } catch (HttpException e) { error = e; } catch (System.Net.Sockets.SocketException e) { error = e; } catch (IOException e) { error = e; } catch (ArgumentException e) { error = e; } catch (InvalidOperationException e) { error = e; } catch (NotSupportedException e) { error = e; } catch (FormatException e) { error = new QuizletException("The Quizlet server returned an invalid document.", e); } catch (JsonConvertException e) { error = new QuizletException("The Quizlet server returned an invalid document.", e); } catch (InvalidCastException e) { error = new QuizletException("The Quizlet server returned an invalid document.", e); } catch (KeyNotFoundException e) { error = new QuizletException("The Quizlet server returned an invalid document.", e); } op.PostOperationCompleted(delegate { errorHandler(error); }, null); }); } catch (OperationCanceledException e) { errorHandler(e); } }