原创  WININET使用简例 收藏

下列代码示范了使用wininet接口的简单方法。

1.用post方式提交两个参数到saveID.jsp, jsp server会暂时记录这两个参数

2.sleep 1秒钟之后,用get方式提交一个参数到getID.jsp ,jsp返回刚才提交的另外一个参数

// http.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "http.h"
#include <afxinet.h>

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// The one and only application object

CWinApp theApp;

using namespace std;

int getID()
{
 CInternetSession session;
 CHttpFile *file = NULL;
 CString strURL = "http://localhost/getID.jsp?argA=113";
 CString strHtml = ""; 

 try
 {
  file = (CHttpFile*)session.OpenURL(strURL);
 }
 catch(CInternetException * m_pException)
 {
  file = NULL;
  m_pException->m_dwError;
  m_pException->Delete();
  session.Close();
  cout<<"CInternetException"<<endl;
 }
 
 CString strLine;
 if(file != NULL)
 {
  while(file->ReadString(strLine) != NULL)
  {
   strHtml += strLine;
  }
 }
 else
 {
  cout<<("fail");
  session.Close();
  return 1;
 }
 session.Close();
 file->Close();
 delete file;
 file = NULL;
 cout<<(LPCTSTR)strHtml<<endl;
 return 1;
}

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
 int nRetCode = 0;

 // initialize MFC and print and error on failure
 if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
 {
  // TODO: change error code to suit your needs
  cerr << _T("Fatal Error: MFC initialization failed") << endl;
  nRetCode = 1;
  return 1;
 }

 CInternetSession m_InetSession(_T("session"), 0, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, INTERNET_FLAG_DONT_CACHE); 
 CHttpConnection* pServer = NULL;
 CHttpFile* pFile = NULL;
 CString strHtml = "";
 CString strRequest = "argA=113&argB=888\r\n"; 

 CString strHeaders = "Accept: */*\r\nReferer: http://www.baidu.com/\r\nAccept-Language: zh-cn\r\nContent-Type: application/x-www-form-urlencoded\r\nAccept-Encoding: gzip, deflate\r\nUser-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
 try
 {
  INTERNET_PORT nPort; 

  nPort=80;
  pServer = m_InetSession.GetHttpConnection("127.0.0.1", nPort);
  pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_POST,"/saveID.jsp");
  pFile->AddRequestHeaders(strHeaders);
  pFile->SendRequestEx(strRequest.GetLength());
  pFile->WriteString(strRequest);  
  pFile->EndRequest();
  DWORD dwRet;
  pFile->QueryInfoStatusCode(dwRet);
  if (dwRet == HTTP_STATUS_OK)
  {
   CString strLine;
   while ((pFile->ReadString(strLine))>0)
   {
    strHtml += strLine;
   }
  }
  delete pFile;
  delete pServer;
 }
 catch (CInternetException* e)
 { e->m_dwContext;}
// cout<<(LPCTSTR)strHtml<<endl;
 cout<<"Submit OK"<<endl;
 Sleep(1000);
 getID();

 return nRetCode;

发表于 @ 2008年04月09日 13:33:00 | 评论( loading... ) | 编辑| 举报| 收藏

旧一篇:static 函数和变量 | 新一篇:标准win32程序框架

  • 发表评论
  • 评论内容:
  •  
Copyright © norbe
Powered by CSDN Blog