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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值