Справочник функций

Ваш аккаунт

Войти через: 
Забыли пароль?
Регистрация
Информацию о новых материалах можно получать и без регистрации:

Почтовая рассылка

Подписчиков: -1
Последний выпуск: 19.06.2015

Заполнение формы Post методом!

471
18 января 2005 года
_MC_
178 / / 13.01.2005
Нужно сделать программу которая бы имела доступ к информации с сайта!
На сайте есть авторизация
 
Код:
<form method='action'>
<input name='login'>
<input name='pass'>
</form>

Ну так вопрос как отправить ПОСТ-запрос при первом посещениий, а потом использовать куки?
471
18 января 2005 года
_MC_
178 / / 13.01.2005



Это немного не то, но все равно спасибо!

Мне нужно не файл послать, а сделать авторизацию, обьясняю (может тупо обясняю но по-другому не могу! :( ):

Есть две страницы index.htm,auth.htm!

Мне нужно получить body от index.htm, но чтобы получить правильный боди (тот что мне нужен) нужно авторизироваться на auth.htm. Т.к. index.htm читает куки, а записываются они именно auth.htm!

Спасибо за внимание, заранее спасибо!

2.3K
18 января 2005 года
ART-CODE
134 / / 15.11.2004
Цитата:
Originally posted by _MC_

нужно авторизироваться на auth.htm. Т.к. index.htm читает куки, а записываются они именно auth.htm!



-1-
Делаешь навигацию на страницу auth.htm
-2-
выдергиваешь HTML - код
http://www.buildercpp.net.ru/phpBB2/viewtopic.php?t=254&highlight=
-3-
Готовишь и отправляешь свой ответ серверу
http://www.buildercpp.net.ru/phpBB2...&highlight=post
-4-
Делаешь навигацию на страницу index.htm

471
18 января 2005 года
_MC_
178 / / 13.01.2005
Цитата:
Originally posted by ART-CODE


-1-
Делаешь навигацию на страницу auth.htm
-2-
выдергиваешь HTML - код


Получить HTML-код не проблема, а что значит готовишь и отправляешь ответ, плиз по-подробнее

Цитата:
Originally posted by ART-CODE
-3-Готовишь и отправляешь свой ответ серверу

471
18 января 2005 года
_MC_
178 / / 13.01.2005
Я же написал конкретно мою задачу!

на auth.htm
 
Код:
<form method='POST' action='auth.htm'>
<input name='login' type='text'>
<input name='pass' type='password'>
</form>


и получить html-код index.htm ичитывая данные веденные ранее!

Извиняюсь в назойливости, но я только начинаю писать программки, поэтому не все сразу понимаю, короче туплю :(
301
18 января 2005 года
lord Kelvin
897 / / 08.11.2004
Цитата:
Originally posted by _MC_
Я же написал конкретно мою задачу!

на auth.htm
 
Код:
<form method='POST' action='auth.htm'>
<input name='login' type='text'>
<input name='pass' type='password'>
</form>


и получить html-код index.htm ичитывая данные веденные ранее!

Извиняюсь в назойливости, но я только начинаю писать программки, поэтому не все сразу понимаю, короче туплю :(


 
Код:
AnsiString data="http://www.blablabla.ru/auth.htm?login=\"lord Kelvin\"&pass=\"****\"";
 NMHTTP1->Get(data);
 Memo1->Text = NMHTTP1->Header;
 Memo2->Text = NMHTTP1->Body;

плюс тебе нужен экзампель из хелпа
Код:
To recreate this example, you will need to create a new blank CBuilder++ application.

Place 4 TMemos, a TEdit, a TOpenDialog, a TNMHTTP, and 7 TButtons on the form.

Component Descriptions

Memo1: Header Display
Memo2: Body Display
Memo3: Status Display
Memo4: Cookie Display
Edit1: URL input
Button1: HTTP Get
Button2: HTTP Head
Button3: HTTP Options
Button4: HTTP Trace
Button5: HTTP Put
Button6: HTTP Post
Button7: HTTP Delete


Insert the following code into Button1's OnClick event:

void __fastcall TForm1::Button1Click(TObject *Sender)
{
  NMHTTP1->Get(Edit1->Text);
}

When Button1 is clicked, the Get method is used to retrieved the document at the address specified by Edit1. Both the document body and the document header are retrieved.


Insert the following code into Button2's OnClick event:

void __fastcall TForm1::Button2Click(TObject *Sender)
{
  NMHTTP1->Head(Edit1->Text);

}

When Button2 is clicked, the Head method is used to retrieve the header of the document at the address specified by Edit1.


Insert the following code into Button3's OnClick event:

void __fastcall TForm1::Button3Click(TObject *Sender)
{
  NMHTTP1->Options(Edit1->Text);
}

When Button3 is clicked, the HTTP options for the document at the address in Edit1 are retrieved using the Options method. Note: Not all servers support the Options method.

Insert the following code into Button4's OnClick event:

void __fastcall TForm1::Button4Click(TObject *Sender)
{
  AnsiString S;
  if (InputQuery("Trace Data Required", "Input data to send as trace", S))
    NMHTTP1->Trace(Edit1->Text, S);
}

When Button4 is clicked, the InputQuery function is used to get data from the user to use as trace data. If the user inputs data and clicks Ok, the Trace method sends the data to the server as trace data.

Insert the following code into Button5's OnClick event:

void __fastcall TForm1::Button5Click(TObject *Sender)
{
  if (OpenDialog1->Execute())
    {
      NMHTTP1->OutputFileMode = TRUE;
      NMHTTP1->Put(Edit1->Text, OpenDialog1->FileName);
      NMHTTP1->OutputFileMode = FALSE;
    }
}

When Button5 is clicked, OpenDialog1 prompts for a file. If a file is selected, the OutputFileMode property is set to TRUE, so that the data to be put will be read from the file specified. The Put method is used to store the file at the address specified by Edit1. When the file is put, the OutputFileMode property is returned to FALSE.

Insert the following code into Button6's OnClick event:

void __fastcall TForm1::Button6Click(TObject *Sender)
{
  AnsiString S;
  if (InputQuery("Post Data Required", "Input data to Post", S))
    NMHTTP1->Post(Edit1->Text, S);
}

When Button6 is clicked, the InputQuery function is used to retrieve the data to be posted. If the Ok button is clicked, the data that was input is posted using the Post method to the document specified by the address in Edit1.

Insert the following code into Button7's OnClick event:

void __fastcall TForm1::Button7Click(TObject *Sender)
{
  NMHTTP1->Delete(Edit1->Text);
}

When Button7 is clicked, the Delete method attempts an HTTP Delete of the document specified by the address in Edit1.

   
Insert the following code into NMHTTP1's OnAuthenticationNeeded event:

void __fastcall TForm1::NMHTTP1AuthenticationNeeded(TObject *Sender)
{
  AnsiString AnID, APass;

  InputQuery("Authentication required", "Enter a user ID", AnID);
  InputQuery("Authentication required", "Enter a password", APass);
  NMHTTP1->HeaderInfo->UserId = AnID;
  NMHTTP1->HeaderInfo->Password = APass;
  ShowMessage("Authentication information in place, please retry the previous command");
}

If basic authentication is used to access the document specified by the address in Edit1, the OnAuthenticationNeeded event is called. In this example, the InputQuery function is used to retrieve a user ID and password. These values are then stored in the UserId and Password properties of the HeaderInfo property (See the THeaderInfo reference). A message is shown to the user asking them to attempt the HTTP transaction again once the password and user id are in place.

Insert the following code into NMHTTP1's OnFailure event:

void __fastcall TForm1::NMHTTP1Failure(CmdType Cmd)
{
  Memo1->Text = NMHTTP1->Header;
  Memo2->Text = NMHTTP1->Body;
  switch(Cmd)
    {
      case CmdGET: Memo3->Lines->Add("HTTP GET Failed");
      case CmdPOST: Memo3->Lines->Add("HTTP Post Failed");
      case CmdHEAD: Memo3->Lines->Add("HTTP HEAD Failed");
      case CmdOPTIONS: Memo3->Lines->Add("HTTP OPTIONS Failed");

      case CmdTRACE: Memo3->Lines->Add("HTTP TRACE Failed");
      case CmdPUT: Memo3->Lines->Add("HTTP PUT Failed");
      case CmdDELETE: Memo3->Lines->Add("HTTP Delete Failed");
    }
}

When an HTTP command fails, the OnFailure event is called. In this case, the header for the returned error is displayed in Memo1, and the body is displayed in Memo2. Memo3 is updated by checking which command failed using the Cmd parameter, and adding a specific fail message for each of the supported commands.

Insert the following code into NMHTTP1's OnRedirect event:

void __fastcall TForm1::NMHTTP1Redirect(bool &Handled)
{
  if (MessageDlg("This site is redirecting you to another site. Allow redirect?", mtConfirmation, TMsgDlgButtons() << mbYes << mbNo, 0) == mrNo)
    Handled = TRUE;
}

If the document specified by the address in Edit1 redirects the client to another site for it's content, the OnRedirect event is called. Using the MessageDlg function, the user is asked to allow the redirect. If the user selects No, the Handled parameter is set to TRUE, which prevents the redirect (default action) from taking place. If the user selects Yes, the default action is taken by the component, and the redirected document is loaded.

Insert the following code into NMHTTP1's OnSuccess event:

void __fastcall TForm1::NMHTTP1Success(CmdType Cmd)
{
  if (NMHTTP1->CookieIn != "")
    Memo4->Text = NMHTTP1->CookieIn;
  Memo1->Text = NMHTTP1->Header;
  Memo2->Text = NMHTTP1->Body;
  switch(Cmd)
    {
      case CmdGET: Memo3->Lines->Add("HTTP GET Successful");
      case CmdPOST: Memo3->Lines->Add("HTTP POST Successful");
      case CmdHEAD: Memo3->Lines->Add("HTTP HEAD Successful");

      case CmdOPTIONS: Memo3->Lines->Add("HTTP OPTIONS Successful");
      case CmdTRACE: Memo3->Lines->Add("HTTP TRACE Successful");
      case CmdPUT: Memo3->Lines->Add("HTTP PUT Successful");
      case CmdDELETE: Memo3->Lines->Add("HTTP DELETE Successful");
    }
}

When an HTTP command succeeds, the OnSuccess event is called, signifying the success. In this example, if a cookie is returned from the remote host in the CookieIn property, it is displayed in Memo4. The header and body returned from the server in the Header and Body properties, respectively. The header is displayed in Memo1, and the body is displayed in Memo2. Memo3 acts as a status screen, displaying that the command specified by the Cmd parameter was successful.

И на закуску - метод пост работает только так NMHTTP1->Post("www.ya.ru","c:\\test.txt"); (В test.txt строка параметров)
2.3K
19 января 2005 года
ART-CODE
134 / / 15.11.2004
NMHTTP1->Get(data);

Согласен, так проще.
НО NMHTTP не умеет работать через SSL, поэтому делать программу, работающюю с защищенным сайтом на этом компоненте не перпективно...

Отправлять пароль и логин Постом и открытым текстом по обычному HTTP - верх пофигизма... :) но это уже вопрос к администратору того сайта.

А еще браузер сам работает с куками (по условию задачи это обязательно), а NMHTTP - не уверен, что он это делает сам.

Исходя из этих соображений я сразу и предложил работать с браузером.

А подготовить ответ серверу совсем просто:

НАПРИМЕР ПОЛУЧЕН ТАКОЙ HTML код страницы
auth.htm
 
Код:
<form Name="PostForm"  action='http://192.168.5.140' method='post' enctype='text' >
<input name='login'>
<input name='pass'>
<input Type=SUBMIT >
</form>

ТОГДА СЕРВЕР ДОЛЖЕН в результате получить это
Код:
POST / HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*
Accept-Language: ru
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.1.4322)
Host: 192.168.5.140:80
Content-Length: 19
Connection: Keep-Alive
Cache-Control: no-cache

login=123&pass=4567

Если есть желание,
можно все это отправить при помощи сокета
Код:
TClientSocket * Request=new TClientSocket(MyProgramForm);

Request->Port=80;
Request->Host="192.168.5.140";
Request->ClientType=ctNonBlocking; //  ctBlocking
Request->&#111;&#110;Connect=ServerConnectionConnect;
Request->&#111;&#110;Error=ServerConnectionError;
Request->&#111;&#110;Disconnect=ServerConnectionDisconnect ;
Request->&#111;&#110;Read=ServerConnectionRead;
Request->&#111;&#110;Write=ServerConnectionWrite;
Request->Open();

Далее в событии OnConnect отправляем данные
 
Код:
void __fastcall TMyProgramForm::ServerConnectionConnect(TObject *Sender,
      TCustomWinSocket *Socket)
{
String post_data="POST / HTTP/1.1\r\nAccept: ...";
// в строку вставить все, что должен получить сервер (см. выше)
Socket->SendBuf(post_data.c_str(),post_data.Length());
}

далее в событии OnRead получить ответ от сервера (вероятно те самые куки)
 
Код:
void __fastcall TMyProgramForm::ServerConnectionRead(TObject *Sender,
      TCustomWinSocket *Socket)
String server_data=Socket->ReceiveText() ;

**************************************************
а на браузере будет так:
заполняем строку
 
Код:
String post_data="login=123&pass=4567";

вызываем функцию:
Код:
WebPostData(WebBrowser,"http://192.168.5.140:80",post_data);

/*
void __fastcall TMyProgramForm::WebPostData(TCppWebBrowser *CppWebBrowser, String sURL, String sPostData)
{
BSTR bstrHeaders = NULL;
TVariant vFlags = {0}, vTargetFrameName={0}, vPostData={0}, vHeaders={0};
LPSAFEARRAY psa;
LPCTSTR cszPostData = sPostData.c_str();
UINT cElems = lstrlen(cszPostData);

LPSTR pPostData;
LPVARIANT pvPostData;

bstrHeaders = SysAllocString(L"Content-Type: application/x-www-form-urlencoded\r\n");

if (!bstrHeaders){
Application->MessageBox("Could not allocate bstrHeaders", "Warning", MB_OK | MB_ICONWARNING);
return;
}

V_VT(&vHeaders) = VT_BSTR;
V_BSTR(&vHeaders) = bstrHeaders;

pvPostData = vPostData;

if(pvPostData){
VariantInit(pvPostData);

psa = SafeArrayCreateVector(VT_UI1, 0, cElems);
if(!psa){
return;
}

SafeArrayAccessData(psa, (LPVOID*)&pPostData);
memcpy(pPostData, cszPostData, cElems);

SafeArrayUnaccessData(psa);

V_VT(pvPostData) = VT_ARRAY | VT_UI1;
V_ARRAY(pvPostData) = psa;

}

CppWebBrowser->Navigate((TVariant)sURL, &vFlags, &vTargetFrameName, &vPostData, &vHeaders);

}
*/
471
20 января 2005 года
_MC_
178 / / 13.01.2005
Огромное спасибо! :)
471
24 января 2005 года
_MC_
178 / / 13.01.2005
Цитата:
Originally posted by ART-CODE

CppWebBrowser->Navigate((TVariant)sURL, &vFlags, &vTargetFrameName, &vPostData, &vHeaders);

}
[/CODE]



ART-CODE, а почему этот код для некоторых сайтов не работает, ты не знаешь?

Реклама на сайте | Обмен ссылками | Ссылки | Экспорт (RSS) | Контакты
Добавить статью | Добавить исходник | Добавить хостинг-провайдера | Добавить сайт в каталог