1

libcurls http 投稿で post_data1 を送信しようとすると、間違ったパスワードが表示されますが、post_data2 で固定式を使用するとログインするという問題があります。両方を計算すると、それらはまったく同じ文字列になります..

libcurl がそれらをヘッダーに入れたときに、なぜそれらが同じではないのか、誰か教えてもらえますか? または、そうである場合、送信する前になぜそれらが異なるのか。

string username = "mads"; string password = "123"; 
stringstream tmp_s;
tmp_s << "username=" << username << "&password=" << password;
static const char * post_data1 = tmp_s.str().c_str();
static const char * post_data2 = "username=mads&password=123";

std::cout << post_data1 << std::endl;  // gives username=mads&password=123
std::cout << post_data2 << std::endl;  // gives username=mads&password=123

// Fill postfields
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_data1);

// Perform the request, res will get the return code
res = curl_easy_perform(curl);
4

3 に答える 3

7

使用すると、一時的なtmp_s.str()文字列を取得します。ポインタを保存することはできません。それをに保存し、呼び出しでその文字列を使用する必要があります。std::string

std::string post_data = tmp_s.str();

// Post the data
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_data.c_str());

curl_easy_setopt 文字列をコピーする場合(そしてポインタだけを保存しない場合のみ)tmp_s、代わりに呼び出しで使用できます。

// Post the data
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, tmp_s.str().c_str());

しかし、関数が文字列をコピーするのか、単にポインタを保存するのかはわかりません。そのため、最初の選択肢(を使用するstd::string)がおそらく最も安全な方法です。

于 2013-03-01T10:21:45.543 に答える
2
static const char * post_data1 = tmp_s.str().c_str();

問題です。文字列オブジェクトを返し、そのオブジェクト内の内部文字列データへのポインタを取得します。次に、文字列はその行の終わりでスコープから外れるため、次にそのメモリにあるものは何でも...へのポインタが残ります。

static std::string str = tmp_s.str();
static const char* post_data1 = str.c_str();

あなたのために働くかもしれません。

于 2013-03-01T10:22:32.060 に答える
0

ストレージ指定子を削除しstatic、コンパイルして実行してみてください。

注:c_str()結果は名目上一時的なものですが、永続的である場合もあります(通常は永続的です)。迅速な修正のために、それはうまくいくかもしれません。

于 2013-03-01T10:25:41.773 に答える