0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C++でHTTP通信 <Visual Studio UWP>

Last updated at Posted at 2022-09-22

C++でサクッとHTTP通信を行うコード。
非同期通信とかのコードを書かなくてもいい(つまり、処理できない)ので、とりあえず試したい時にはこれで!

http_get.cpp

using namespace winrt;
using namespace Windows::Foundation;
using namespace Windows::Storage::Streams;
using namespace Windows::Web::Http;

bool http_get(){
    Windows::Web::Http::HttpClient httpClient;
    Windows::Web::Http::HttpResponseMessage httpResponseMessage;
    std::wstring httpResponseBody;

    Uri requestUri{ L"http://localhost/api/token"};
    try {
        // Send the GET request.
        httpResponseMessage = httpClient.GetAsync(requestUri).get();
        if( !httpResponseMessage.IsSuccessStatusCode() ) {
            return false;
        }

    } catch( winrt::hresult_error const& ex ) {
        //httpResponseBody = ex.message();
        return false ;
    }
    return true;
}

bool http_post(Config config) {
    Windows::Web::Http::HttpClient httpClient;
    Windows::Web::Http::HttpResponseMessage httpResponseMessage;
    std::wstring httpResponseBody;
    
    Uri requestUri{ L"http://localhost/api/token"};
    //POSTデータをJSON形式で作成
    HttpStringContent content( 
        L"{ \"login_id\" : \"" + config.getUID() + L"\", \"password\" : \"" + config.getPWD() + L"\"}",
        UnicodeEncoding::Utf8,
        L"application/json"
    );

    try {
        httpResponseMessage = httpClient.PostAsync(requestUri, content).get();
        if( httpResponseMessage.IsSuccessStatusCode() ) {
            httpResponseBody = httpResponseMessage.Content().ReadAsStringAsync().get();
            JsonObject val = JsonObject::Parse(httpResponseBody);
            //JSONのデータ抽出処理
        } else {
            //エラー処理
            return false;
        }

    } catch( winrt::hresult_error const& ex ) {
        //例外エラー処理
        return false;
    }

    return true;
}

http_getはGET形式。
http_postはPOST方式(ファイルアップロードではない)

▼参考記事

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?