Haruyuki Mohri

毛利春幸のブログです。

TNetHTTPClient, TNetHTTPRequest Post

TNetHTTPClient, TNetHTTPRequest Post

dfmファイル

object Form1: TForm1
  Caption = 'Form1'
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  PixelsPerInch = 96
  TextHeight = 13
  object Button1: TButton
    Left = 8
    Top = 8
    Width = 249
    Height = 25
    Caption = 'Button1'
    TabOrder = 0
    OnClick = Button1Click
  end
  object Memo1: TMemo
    Lines.Strings = (
      'Memo1')
    TabOrder = 1
  end
  object Panel1: TPanel
    Caption = 'Panel1'
    ShowCaption = False
    TabOrder = 2
    Visible = False
    object ActivityIndicator1: TActivityIndicator
      Left = 96
      Top = 49
    end
  end
end

cppファイル

#include <System.Net.HttpClient.hpp>
#include <System.Net.HttpClientComponent.hpp>
#include <System.Net.URLClient.hpp>

void __fastcall TForm1::Button1Click(TObject *Sender)
{
    ActivityIndicator1->Animate = True;
    Button1->Enabled = False;
    Panel1->Top = 0;
    Panel1->Left = 0;
    Panel1->Visible = True;
    TThread::CreateAnonymousThread([this](){
        Sleep(100);
        std::shared_ptr<TMultipartFormData> md = std::shared_ptr<TMultipartFormData>(new TMultipartFormData(NULL));
        std::shared_ptr<TNetHTTPClient> ncl = std::shared_ptr<TNetHTTPClient>(new TNetHTTPClient(NULL) );
        std::shared_ptr<TNetHTTPRequest> nreq = std::shared_ptr<TNetHTTPRequest>(new TNetHTTPRequest(NULL) );
        try
        {
            try
            {
                nreq->Client = ncl.get();

                //POSTで送りたい内容
                md->AddField("hoge1", "aho1");
                md->AddField("hoge2", "aho2");

                //カスタムぽいヘッダーを作る
                TNetHeaders h;
                h.Length = 1;
                h[0] = TNameValuePair("Referer","http://aaa.co.jp");

                //UserAgentを入れる
                ncl->UserAgent = "Mozilla/5.0";

                _di_IHTTPResponse resp;

                //Post接続
                resp = nreq->Post("http://docwiki.embarcadero.com/Libraries/Berlin/en/Main_Page", md.get(), nullptr, h);

                TThread::Synchronize(TThread::CurrentThread, [this, resp](){
                    Memo1->Lines->Append(
                        resp->ContentAsString(TEncoding::UTF8) //Response内容
                        );
                });
            }
            catch(Exception &ex)
            {
                //Errorの時の処理
            }
        }
        __finally
        {

            TThread::Synchronize(TThread::CurrentThread, [this](){
                Panel1->Visible = False;
                ActivityIndicator1->Animate = False;
                Button1->Enabled = True;
            });
        }

    })->Start();


}

f:id:mojeld:20160615192340j:plain