VC实现发送微博消息

来源:互联网 发布:淘宝如何购买流量 编辑:程序博客网 时间:2024/06/05 07:20
//发送的微博能够实现中文显示
//转码 ANSI字符集下将CString转化成UTF-8char * ConvertANSIToUTF8(CString &strANSI)   {   int nLen = ::MultiByteToWideChar(CP_ACP,MB_ERR_INVALID_CHARS,(LPCTSTR)strANSI,-1,NULL,0);   unsigned short * wszUTF_8 = new unsigned short[nLen+1];   memset(wszUTF_8, 0, nLen * 2 + 2);   nLen = MultiByteToWideChar(CP_ACP, 0, (LPCTSTR)strANSI, -1, wszUTF_8, nLen);   nLen = WideCharToMultiByte(CP_UTF8, 0, wszUTF_8, -1, NULL, 0, NULL, NULL);       char *szUTF8=new char[nLen + 1];       memset(szUTF8, 0, nLen + 1);       WideCharToMultiByte (CP_UTF8, 0, wszUTF_8, -1, szUTF8, nLen, NULL,NULL);   //strANSI = szUTF8;//delete wszUTF_8;  //delete szUTF8;return szUTF8;}

 

登录微博并保存cookie:

static CString MyCookie;void CMovisionDlg::OnSendRequest() {//if(m_UserEmail.GetLength()==0)//{//AfxMessageBox("邮箱不能为空!");//return;//}CString str1,str2;GetDlgItem(IDC_EDIT1)->GetWindowText(str1);//邮箱GetDlgItem(IDC_EDIT2)->GetWindowText(str2);//密码if(str1 == "" || str2 == ""){AfxMessageBox("邮箱或密码不能为空!");//AfxMessageBox(str1);return;}CInternetSession sess;//建立会话sess.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, 1000 * 20);sess.SetOption(INTERNET_OPTION_CONNECT_BACKOFF, 1000);sess.SetOption(INTERNET_OPTION_CONNECT_RETRIES, 1);//CHttpFile *pf = (CHttpFile *)sess.OpenURL("http://www.baidu.com");//连接到http服务器CHttpConnection *conn = sess.GetHttpConnection(TEXT("weibo.kedacom.com"),(INTERNET_PORT)8080);//打开http请求CHttpFile *pf = conn->OpenRequest(CHttpConnection::HTTP_VERB_POST,  TEXT("/login/weiboLogin"),  NULL,  1,  NULL,  TEXT("HTTP/1.1"),  INTERNET_FLAG_RELOAD);//需要提交的数据CString szHeaders = L"Content-type:application/x-www-form-urlencoded;content=UTF-8;";CString strFormData1 = "encode=false&password="+str2+"&rememberMe=true&username="+str1;BOOL isok = pf->SendRequest(szHeaders,szHeaders.GetLength(),(LPVOID)(LPCTSTR)strFormData1,strlen(strFormData1));//登陆后获取cookiechar * pszURL = "http://weibo.kedacom.com";//url一定要加上http,否则无法识别CString strCookie;if(sess.GetCookie(pszURL,"",strCookie)){MyCookie = strCookie;DWORD dwValue = sess.GetCookieLength("http://weibo.kedacom.com",strCookie);if(dwValue<400){CString str;str.Format("%d",GetLastError());AfxMessageBox("邮箱或密码错误!");m_UserEmail = "";m_UserPwd = "";UpdateData(FALSE);return;}}GetDlgItem(IDC_EDIT1)->EnableWindow(FALSE);//设为只读GetDlgItem(IDC_EDIT2)->EnableWindow(FALSE);DWORD dwRet;//获取请求的状态码pf->QueryInfoStatusCode(dwRet);//Http 的状态码主要有以下几类: //Group     Meaning//200-299   Success//300-399   Information//400-499   Request error//500-599   Server error//更详细的代码参数: //Status code         Meaning//200           URL located, transmission follows//400           Unintelligible request//404           Requested URL not found//405           Server does not support requested method//500           Unknown server error//503           Server capacity reachedif(dwRet != HTTP_STATUS_OK){CString errText;errText.Format("POST出错,错误码 %d",dwRet);AfxMessageBox(errText);}else{CString okText;okText.Format("登录成功!");AfxMessageBox(okText);//int len = pf->GetLength();//char buf[2000];//int numread;//CString filepath;//CString strFile = L"result1.html";//filepath.Format(".\\%s", strFile);//CFile myfile(filepath,CFile::modeCreate|CFile::modeWrite|CFile::typeBinary);//while ((numread = pf->Read(buf,sizeof(buf)-1)) > 0)//{//buf[numread] = '\0';//strFile += buf;//myfile.Write(buf, numread);//}//myfile.Close();}//发送http请求//pf->SendRequest();//从服务器读取字节流//CString str,tmp;//while(pf->ReadString(tmp))//{//str+=tmp;//}//if(result)//{//AfxMessageBox(_T("请求成功!"));//}//CString szData,szAlldata;//while(pf->ReadString(szData))//{//读取文件//szAlldata+="\r\n";//szAlldata+=szData;//}pf->Close();conn->Close();delete pf;//AfxMessageBox(str);//Sleep(1000);//ShellExecute(NULL,"open","iexplore.exe","http://weibo.kedacom.com/home",NULL,SW_SHOWNORMAL);}

 

发送微博:

void CMovisionDlg::OnButton4() {//AfxMessageBox(MyCookie);if(MyCookie == ""){AfxMessageBox("请先登录!!");return;}CString strHost = _T("weibo.kedacom.com");      CString strUrl = _T("/feed");      INTERNET_PORT m_Port = 8080;      CInternetSession m_Session(_T("HttpClient"));      CHttpConnection * m_Server = NULL;    CHttpFile * m_File = NULL;  //发送的微博的内容CString myContent;GetDlgItem(IDC_EDIT3)->GetWindowText(myContent);if(myContent == ""){AfxMessageBox("发送内容不能为空!");return;}//char* buf = myContent.GetBuffer(myContent.GetLength());//提交的数据  CString strRequest = "";strRequest =strRequest+"body="+ConvertANSIToUTF8(myContent)+"&groupId=265&deptSpaceId=0&categoryLevel1=0&categoryLevel2=0&clientType=Web&attachmentJSON=&attachmentNum=0";CString strHeader = "Content-Type:application/x-www-form-urlencoded;charset:UTF-8";m_Server = m_Session.GetHttpConnection(strHost,m_Port);          if(m_Server == NULL){            AfxMessageBox("CHttpConnection failed!");  }        m_File = m_Server->OpenRequest(CHttpConnection::HTTP_VERB_POST,strUrl);        if (m_File == NULL){            AfxMessageBox("CHttpFile is NULL!");}m_File->AddRequestHeaders(_T("POST /feed HTTP/1.1"));m_File->AddRequestHeaders(_T("HOST:weibo.kedacom.com"));        m_File->AddRequestHeaders(strHeader);m_File->AddRequestHeaders(_T("Referer:http://weibo.kedacom.com/home#"));//m_File->AddRequestHeaders(_T("Content-Length:112"));m_File->AddRequestHeaders(_T("User-Agent:Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; .NET4.0E)"));m_File->AddRequestHeaders(_T("Accept:application/json, text/javascript, */*; q=0.01"));        m_File->AddRequestHeaders(_T("Accept-Language:zh-cn"));//特别这个头的部分,如果请求包头错误,那么肯定不会成功        m_File->AddRequestHeaders(_T("Accept-Encoding:gzip,deflate"));m_File->AddRequestHeaders(_T("X-Requested-With:XMLHttpRequest"));m_File->AddRequestHeaders(_T("Cookie:"+MyCookie));m_File->AddRequestHeaders(_T("Connection:keep-alive"));m_File->AddRequestHeaders(_T("Cache-Control:no-cache"));m_File->SendRequest(strHeader,(LPVOID)(LPCTSTR)strRequest,strRequest.GetLength());//获取请求的状态码DWORD dwRet;m_File->QueryInfoStatusCode(dwRet);if(dwRet != HTTP_STATUS_OK){CString errText;errText.Format("POST出错!错误码 %d",dwRet);AfxMessageBox(errText);}else{CString okText;okText.Format("发送成功!");AfxMessageBox(okText);Sleep(1000);//ShellExecute(NULL,"open","firefox.exe","172.16.217.149/meeting",NULL,SW_SHOWNORMAL);m_File->Close();m_Server->Close();delete m_File;delete m_Server;}}


到此,实现基本功能。附效果图一张: