/** * 短信接口-新 */ func SendSmsNew(phone, msg string) (err error) { defer func() { if x := recover(); x != nil { errStr := fmt.Sprintf("Send sms fail: phone-%s, msg-%s, err-%v", phone, msg, x) err = errors.New(errStr) } }() phone = strings.TrimSpace(phone) msg = strings.TrimSpace(msg) if phone == "" || msg == "" { return errors.New("无效参数") } req := httplib.Post("http://sms.uboxol.com/send_sms").SetTimeout(CONNECT_TIME_OUT, READ_WRITE_TIME_OUT).Header("Content-Type", "application/x-www-form-urlencoded") req.Param("phone", phone) req.Param("msg", msg) req.Param("caller", "predetermine") resp := &SmsResp{} err = req.ToJson(resp) fmt.Println(resp, err.Error()) return nil }
// 获取github token func (this *CheckController) GetToken() { ok, data := func() (bool, interface{}) { //获取并注销session if this.GetSession("state") == nil { return false, "请求已失效" } state := this.GetSession("state").(int32) this.DelSession("state") //验证state是否正确 postState, _ := this.GetInt32("state") if postState != state { return false, "state错误" } req := httplib.Post("https://github.com/login/oauth/access_token") req.Param("client_id", beego.AppConfig.String("ClientId")) req.Param("client_secret", beego.AppConfig.String("ClientSecret")) req.Param("code", this.GetString("code")) result, _ := req.String() return true, result }() this.Data["json"] = map[string]interface{}{ "ok": ok, "data": data, } this.ServeJson() }
func (m MasterApi) DownloadDataSetSplit(id, splitNumber, index int64) (string, error) { req := httplib.Post(fmt.Sprintf("http://%s/v1/data_set/download", m.Hostname)) req = req.Param("id", strconv.FormatInt(id, 10)) req = req.Param("splitNumber", strconv.FormatInt(splitNumber, 10)) req = req.Param("index", strconv.FormatInt(index, 10)) resp, err := req.Response() if err != nil { return "", err } defer resp.Body.Close() if resp.StatusCode != 200 { return "", ErrApiFailed } filename := strings.TrimPrefix(resp.Header.Get("Content-Disposition"), "attachment; filename=") body, err := ioutil.ReadAll(resp.Body) if err != nil { return "", err } err = ioutil.WriteFile("../tmp/"+filename, body, 0) if err != nil { return "", err } return filename, nil }
func main() { /*defer func(){ recover() fmt.Println("recover from panic") }() */ //post********************** req := httplib.Post("http://localhost:8080/users") for i := 1; i < 10000; i++ { //req.Param("id",fmt.Sprintf("%d",i)) //req.Param("name",fmt.Sprintf("name%d",i)) // fmt.Println(i) // req.Param("id","1") //req.Param("{\"name\":\"jac\"}") //req.Param("name","hehe") req.Body(fmt.Sprintf("{\"name\":\"jac%d\"}", i)) //for json ,must use Body method,key=value is not right result, err := req.String() if err != nil { fmt.Println("error") fmt.Println(err) } else { fmt.Println(result) } } /* str, err := httplib.Get("http://localhost:8080/users").String() if err != nil { //t.Fatal(err) fmt.Println(err) //panic("error in httplib") } fmt.Println(str) */ }
func (m MasterApi) AcquireJobSlice() (*models.JobSlice, error) { req := httplib.Post(fmt.Sprintf("http://%s/v1/job_slice/acquire", m.Hostname)) resp, err := req.Response() if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != 200 { if resp.StatusCode == 204 { return nil, ErrNoMoreData } else { return nil, ErrApiFailed } } body, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } js := models.JobSlice{} err = json.Unmarshal(body, &js) if err != nil { return nil, err } return &js, nil }
func (m MasterApi) AcquireId() (int64, error) { req := httplib.Post(fmt.Sprintf("http://%s/v1/node/acquire", m.Hostname)) resp, err := req.Response() if err != nil { return -1, err } defer resp.Body.Close() if resp.StatusCode != 200 { return -1, ErrApiFailed } body, err := ioutil.ReadAll(resp.Body) if err != nil { return -1, err } id, err := strconv.ParseInt(string(body), 10, 64) if err != nil { return -1, err } return id, nil }
func main() { defer func() { if x := recover(); x != nil { fmt.Println(x) } }() req := httplib.Post(`http://192.168.8.30:8084/rest/release/soldout/`) req.Header("Content-type", "text/plain;charset=UTF-8") data := `{"vmCodes":[{"vmCode":"0001407","sn":"223389047060430848","ctime":"2014-09-08 00:00:01"},{"vmCode":"0001407","sn":"256","ctime":"2014-09-08 00:00:01"}]}` fmt.Println(data) req.Param("data", data) // resp := &ApiResp{} str, err := req.String() if err != nil { fmt.Println(err.Error()) return } fmt.Println(str) // // err := req.ToJson(resp) // if err != nil { // return // } // var sellResults []*SellResult // //获取body数据 // err = GetRespBodyData(resp, &sellResults) // fmt.Println(resp.Head, sellResults) return }
//获取被封禁用户 方法 func (rcServer *RCServer) UserBlockQuery() ([]byte, error) { destinationUrl := rcServer.apiUrl + RC_USER_BLOCK_QUERY + rcServer.format req := httplib.Post(destinationUrl) fillHeader(req, rcServer) byteData, err := req.Bytes() return byteData, err }
/** * 获取http请求结果,只支持post,返回结构自定义 * url:请求地址 * params:post参数 * data:返回数据 */ func GetPostHttpRequestData(url string, params map[string]string, respData interface{}) (err error) { defer func() { if x := recover(); x != nil { errStr := fmt.Sprintf("get post fail: params-%v , err-%v", params, x) err = errors.New(errStr) } }() begin := time.Now().UnixNano() req := httplib.Post(url).SetTimeout(CONNECT_TIME_OUT, READ_WRITE_TIME_OUT).Header("Content-Type", "application/x-www-form-urlencoded") beego.Info("Request url:", url, params) if params != nil && len(params) > 0 { for key, value := range params { req.Param(key, value) } } err = req.ToJson(respData) if err != nil { return } end := time.Now().UnixNano() beego.Info("Http response:", respData, ", cost:", end-begin) return }
// getRepo downloads package data and returns 'Package' by given import path and tag. // It returns error when error occurs in the underlying functions. func getRepo(client *http.Client, path, tag, ptag string) (pdoc *hv.Package, err error) { switch { case utils.IsGoRepoPath(path): pdoc, err = getStandardDoc(client, path, tag, ptag) case utils.IsValidRemotePath(path): pdoc, err = getStatic(client, path, tag, ptag) if err == errNoMatch { pdoc, err = getDynamic(client, path, tag, ptag) } default: return nil, errors.New( fmt.Sprintf("doc.getRepo -> No match( %s:%s )", path, tag)) } if pdoc == nil { return nil, err } pdoc.PkgVer = hv.PACKAGE_VER // Render README. for name, content := range pdoc.Readme { p, err := httplib.Post("https://api.github.com/markdown/raw?"+GetGithubCredentials()). Header("Content-Type", "text/plain").Body(content).Bytes() if err != nil { return nil, errors.New( fmt.Sprintf("doc.getRepo -> Render README( %s:%s ): %v", path, tag, err)) } pdoc.Readme[name] = p } return pdoc, err }
//comp file func backUp() { backUpFile := beego.AppName + "_" + time.Now().Format("060102") + ".zip" fw, err := os.Create(backUpFile) if err != nil { beego.Error(err) return } defer fw.Close() zw := zip.NewWriter(fw) defer zw.Close() walk := func(path string, info os.FileInfo, err error) error { if err != nil { return err } if info.IsDir() { return nil } src, _ := os.Open(path) defer src.Close() h := &zip.FileHeader{Name: path, Method: zip.Deflate, Flags: 0x800} fileName, _ := zw.CreateHeader(h) io.Copy(fileName, src) zw.Flush() return nil } if err := filepath.Walk(enum.CONST.DBNAME, walk); err != nil { beego.Error(err) return } if err := filepath.Walk(enum.CONST.UPLOADPATH, walk); err != nil { beego.Error(err) return } //file upload req := httplib.Post(url) req.Header("Authorization", dropboxAuthorization) req.Header("Dropbox-API-Arg", fmt.Sprintf(argF, beego.AppName, backUpFile)) req.Header("Content-Type", "application/octet-stream") data, err := ioutil.ReadFile(backUpFile) if err != nil { beego.Error(err) return } req.Body(data) resp, err := req.SendOut() if err != nil || resp.StatusCode != http.StatusOK { beego.Error(err, resp) } //file delete os.Remove(backUpFile) }
func test3() { url := "http://localhost:8081/test" req := httplib.Post(url) req.Param("username", "guojing") req.Param("password", "123456") b, _ := req.Bytes() fmt.Println(string(b)) }
//查询聊天室信息 方法 func (rcServer *RCServer) ChatroomQuery(chatroomId string) ([]byte, error) { destinationUrl := rcServer.apiUrl + RC_CHATROOM_QUERY + rcServer.format req := httplib.Post(destinationUrl) req.Param("chatroomId", chatroomId) fillHeader(req, rcServer) byteData, err := req.Bytes() return byteData, err }
//消息历史记录删除 方法 //说明:删除 APP 内指定某天某小时内的所有会话消息记录 func (rcServer *RCServer) MessageHistoryDelete(date string) ([]byte, error) { destinationUrl := rcServer.apiUrl + RC_MESSAGE_HISTORY_DELETE + rcServer.format req := httplib.Post(destinationUrl) req.Param("date", date) fillHeader(req, rcServer) byteData, err := req.Bytes() return byteData, err }
//获取某用户的黑名单列表 方法 func (rcServer *RCServer) UserBlackQuery(userId string) ([]byte, error) { destinationUrl := rcServer.apiUrl + RC_USER_BLACK_QUERY + rcServer.format req := httplib.Post(destinationUrl) req.Param("userId", userId) fillHeader(req, rcServer) byteData, err := req.Bytes() return byteData, err }
//解除用户封禁 方法 func (rcServer *RCServer) UserUnblock(userId string) ([]byte, error) { destinationUrl := rcServer.apiUrl + RC_USER_UNBLOCK + rcServer.format req := httplib.Post(destinationUrl) req.Param("userId", userId) fillHeader(req, rcServer) byteData, err := req.Bytes() return byteData, err }
//检查用户在线状态 方法 //请不要频繁循环调用此接口,而是选择合适的频率和时机调用,此接口设置了一定的频率限制。 func (rcServer *RCServer) UserCheckOnline(userId string) ([]byte, error) { destinationUrl := rcServer.apiUrl + RC_USER_CHECK_ONLINE + rcServer.format req := httplib.Post(destinationUrl) req.Param("userId", userId) fillHeader(req, rcServer) byteData, err := req.Bytes() return byteData, err }
//创建聊天室 方法 func (rcServer *RCServer) ChatroomCreat(chatroomId, chatroomName string) ([]byte, error) { destinationUrl := rcServer.apiUrl + RC_CHATROOM_CREATE + rcServer.format req := httplib.Post(destinationUrl) req.Param("chatroom["+chatroomId+"]", chatroomName) fillHeader(req, rcServer) byteData, err := req.Bytes() return byteData, err }
//刷新群组信息 方法 func (rcServer *RCServer) GroupRefresh(groupId, groupName string) ([]byte, error) { destinationUrl := rcServer.apiUrl + RC_GROUP_REFRESH + rcServer.format req := httplib.Post(destinationUrl) req.Param("groupId", groupId) req.Param("groupName", groupName) fillHeader(req, rcServer) byteData, err := req.Bytes() return byteData, err }
//解散群组 方法 //将该群解散,所有用户都无法再接收该群的消息。 func (rcServer *RCServer) GroupDismiss(userId, groupId string) ([]byte, error) { destinationUrl := rcServer.apiUrl + RC_GROUP_DISMISS + rcServer.format req := httplib.Post(destinationUrl) req.Param("userId", userId) req.Param("groupId", groupId) fillHeader(req, rcServer) byteData, err := req.Bytes() return byteData, err }
func post(url string, params map[string]string, v interface{}) error { req := httplib.Post(url) if len(params) > 0 { for key, val := range params { req.Param(key, val) } } return req.ToJson(v) }
//发送广播消息 方法 //说明:某发送消息给一个应用下的所有注册用户。 //此服务尚未公开提供。如您需要,请提交工单给我们登记。 func (rcServer *RCServer) MessageBroadcast(fromUserId, objectName, content string) ([]byte, error) { destinationUrl := rcServer.apiUrl + RC_MESSAGE_BROADCAST + rcServer.format req := httplib.Post(destinationUrl) req.Param("fromUserId", fromUserId) req.Param("objectName", objectName) req.Param("content", content) fillHeader(req, rcServer) byteData, err := req.Bytes() return byteData, err }
func (p *missoAuth) GenerateCredential() (string, error) { url := p.missoAuthDomain + "/login/broker_cookies" req := httplib.Post(url) req.Param("broker_name", p.BrokerName) req.Param("secret_key", p.SecretKey) resp, err := req.SetTimeout(3*time.Second, 3*time.Second).String() p.Credential = resp return resp, err }
//刷新用户信息 方法 func (rcServer *RCServer) UserRefresh(userId, name, portraitUri string) ([]byte, error) { destinationUrl := rcServer.apiUrl + RC_USER_REFRESH + rcServer.format req := httplib.Post(destinationUrl) req.Param("userId", userId) req.Param("name", name) req.Param("portraitUri", portraitUri) fillHeader(req, rcServer) byteData, err := req.Bytes() return byteData, err }
//退出群组 方法 //将用户从群中移除,不再接收该群组的消息。 func (rcServer *RCServer) GroupQuit(userIdArray []string, groupId string) ([]byte, error) { destinationUrl := rcServer.apiUrl + RC_GROUP_QUIT + rcServer.format req := httplib.Post(destinationUrl) for _, userId := range userIdArray { req.Param("userId", userId) } req.Param("groupId", groupId) fillHeader(req, rcServer) byteData, err := req.Bytes() return byteData, err }
//同步消息 方法 //同步消息时都需要你的服务提供应答,只要有应答,就表示消息已经同步,如果无应答或者应答超时(10秒),融云会再尝试推送2次,如果仍然失败,融云将不再推送此消息。 //说明: //1、融云服务器可以将消息数据同步给开发者的应用服务器,开发者应用服务器接收所有在你的 App 下聊天的实时数据(目前支持二人会话数据、群聊数据),接收数据前需要在开发者后台注册接收地址(目前通过工单提交)。 //2、为了验证数据有效性并确保调用者为融云 Server,我们会在每个请求前添加数据签名,详细签名方法参见“API 调用签名规则”,签名信息参数在接收地址的 URL 上提供。 //3、调用 Server API 接口发送的消息,不会通过消息路由服务。 func (rcServer *RCServer) MessageReceive(messageReceiveURL, fromUserId, toUserId, objectName, content, timestamp string) ([]byte, error) { destinationUrl := messageReceiveURL req := httplib.Post(destinationUrl) req.Param("fromUserId", fromUserId) req.Param("toUserId", toUserId) req.Param("objectName", objectName) req.Param("content", content) req.Param("timestamp", timestamp) fillHeader(req, rcServer) byteData, err := req.Bytes() return byteData, err }
//http调用远程接口 func Call(addr string, params map[string]string) *models.Result { req := httplib.Post(addr).SetTimeout(3000*time.Millisecond, 3000*time.Millisecond) for k, v := range params { req.Param(k, v) } res, err := req.String() if err != nil { return models.NewErrorResult(nil) } result := models.NewResult(res) return result }
//同步用户所属群组 方法 //向融云服务器提交 userId 对应的用户当前所加入的所有群组。 func (rcServer *RCServer) GroupSync(userId string, groupIdAndNameArray []map[string]string) ([]byte, error) { destinationUrl := rcServer.apiUrl + RC_GROUP_SYNC + rcServer.format req := httplib.Post(destinationUrl) req.Param("userId", userId) for _, groupIdAndNameDic := range groupIdAndNameArray { for groupId, name := range groupIdAndNameDic { req.Param("groupId["+groupId+"]", name) } } fillHeader(req, rcServer) byteData, err := req.Bytes() return byteData, err }
//发送聊天室消息 方法 //说明:一个用户向聊天室发送消息 func (rcServer *RCServer) MessageChatroomPublish(fromUserId string, toChatroomIds []string, objectName, content string) ([]byte, error) { destinationUrl := rcServer.apiUrl + RC_MESSAGE_CHATROOM_PUBLISH + rcServer.format req := httplib.Post(destinationUrl) req.Param("fromUserId", fromUserId) for _, toChatroomId := range toChatroomIds { req.Param("toChatroomId", toChatroomId) } req.Param("objectName", objectName) req.Param("content", content) fillHeader(req, rcServer) byteData, err := req.Bytes() return byteData, err }
func (this *Action) httpClientTest() { req := httplib.Get("http://www.baidu.com/") str, err := req.String() if err != nil { Error(err) } Debug(len(str)) str, err = httplib.Post("http://www.baidu.com/").SetTimeout(100*time.Second, 30*time.Second).Param("wd", "go").String() if err != nil { Error(err) } Debug(len(str)) }