如何从 C++ 打开 URL?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17347950/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 21:07:03  来源:igfitidea点击:

How do I open a URL from C++?

htmlc++unixurlbrowser

提问by rodrigoalvesvieira

how can I open a URL from my C++ program?

如何从我的 C++ 程序打开 URL?

In ruby you can do

在红宝石中你可以做

%x(open https://google.com)

What's the equivalent in C++? I wonder if there's a platform-independent solution. But if there isn't, I'd like the Unix/Mac better :)

C++ 中的等价物是什么?我想知道是否有独立于平台的解决方案。但如果没有,我更喜欢 Unix/Mac :)

Here's my code:

这是我的代码:

#include <stdio.h>
#include <string.h>
#include <fstream>

int main (int argc, char *argv[])
{
    char url[1000] = "https://www.google.com";

    std::fstream fs;
    fs.open(url);
    fs.close();

    return 0;
}

回答by ST3

Your question may mean two different things:

你的问题可能意味着两件事:

1.) Open a web page with a browser.

1.) 用浏览器打开一个网页。

#include <windows.h>
#include <shellapi.h>
...
ShellExecute(0, 0, L"http://www.google.com", 0, 0 , SW_SHOW );

This should work, it opens the file with the associated program. Should open the browser, which is usually the default web browser.

这应该可以工作,它会使用关联的程序打开文件。应该打开浏览器,这通常是默认的 Web 浏览器。



2.) Get the code of a webpage and you will render it yourself or do some other thing. For this I recommend to read thisor/and this.

2.) 获取网页的代码,您将自己渲染它或做其他事情。为此,我建议阅读或/和



I hope it's at least a little helpful.

我希望它至少有点帮助。

EDIT: Did not notice, what you are asking for UNIX, this only work on Windows.

编辑:没有注意到,您对 UNIX 的要求是什么,这只适用于 Windows。

回答by rectummelancolique

Use libcurl, here is a simple example.

使用libcurl,这里是一个简单的例子

EDIT: If this is about starting a web browser from C++, you can invoke a shell command with systemon a POSIX system:

编辑:如果这是关于从 C++ 启动 Web 浏览器,您可以system在 POSIX 系统上调用 shell 命令:

system("<mybrowser> http://google.com");

By replacing <mybrowser>with the browser you want to launch.

通过替换<mybrowser>为您要启动的浏览器。

回答by Software_Designer

Here's an example in windows code using winsock.

这是使用 winsock 的 Windows 代码示例。

#include <winsock2.h>
#include <windows.h>
#include <iostream>
#include <string>
#include <locale>
#pragma comment(lib,"ws2_32.lib")
using namespace std;

string website_HTML;
locale local;


void get_Website(char *url );

int main ()
{
    //open website
    get_Website("www.google.com" );

    //format website HTML
    for (size_t i=0; i<website_HTML.length(); ++i) 
        website_HTML[i]= tolower(website_HTML[i],local);

    //display HTML
    cout <<website_HTML;

    cout<<"\n\n";



    return 0;
}



//***************************
void get_Website(char *url )
{
    WSADATA wsaData;
    SOCKET Socket;
    SOCKADDR_IN SockAddr;


    int lineCount=0;
    int rowCount=0;

    struct hostent *host;
    char *get_http= new char[256];

        memset(get_http,' ', sizeof(get_http) );
        strcpy(get_http,"GET / HTTP/1.1\r\nHost: ");
        strcat(get_http,url);
        strcat(get_http,"\r\nConnection: close\r\n\r\n");

        if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) 
        {
            cout << "WSAStartup failed.\n";
            system("pause");
            //return 1;
        }

        Socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
        host = gethostbyname(url);

        SockAddr.sin_port=htons(80);
        SockAddr.sin_family=AF_INET;
        SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);

        cout << "Connecting to "<< url<<" ...\n";

        if(connect(Socket,(SOCKADDR*)(&SockAddr),sizeof(SockAddr)) != 0)
        {
            cout << "Could not connect";
            system("pause");
            //return 1;
        }

        cout << "Connected.\n";     
        send(Socket,get_http, strlen(get_http),0 );

        char buffer[10000];

        int nDataLength;
            while ((nDataLength = recv(Socket,buffer,10000,0)) > 0)
            {       
                int i = 0;

                while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') 
                {                    
                    website_HTML+=buffer[i];                     
                    i += 1;
                }               
            }
        closesocket(Socket);
        WSACleanup();

            delete[] get_http;
}

回答by ahogen

I've had MUCH better luck using ShellExecuteA(). I've heard that there are a lot of security risks when you use "system()". This is what I came up with for my own code.

我使用 ShellExecuteA() 的运气要好得多。我听说使用“system()”时存在很多安全风险。这是我为自己的代码想出的。

void SearchWeb( string word )
{    
    string base_URL = "http://www.bing.com/search?q=";
    string search_URL = "dummy";
    search_URL = base_URL + word;

    cout << "Searching for: \"" << word << "\"\n";

    ShellExecuteA(NULL, "open", search_URL.c_str(), NULL, NULL, SW_SHOWNORMAL);
}

p.s. Its using WinAPI if i'm correct. So its not multiplatform solution.

ps 如果我是对的,它使用 WinAPI。所以它不是多平台解决方案。

回答by ahogen

C isn't as high-level as the scripting language you mention. But if you want to stay away from socket-based programming, try Curl. Curl is a great C library and has many features. I have used it for years and always recommend it. It also includes some stand alone programs for testing or shell use.

C 不像你提到的脚本语言那么高级。但是,如果您想远离基于套接字的编程,请尝试 Curl。Curl 是一个很棒的 C 库并且有很多特性。我已经使用它多年并且总是推荐它。它还包括一些用于测试或 shell 使用的独立程序。

回答by recolic

There're already answers for windows. In linux, I noticed open https://www.google.comalways launch browser from shell, so you can try:

Windows 已经有了答案。在 linux 中,我注意到open https://www.google.com总是从 shell 启动浏览器,所以你可以尝试:

system("open https://your.domain/uri");

system("open https://your.domain/uri");

that's say

也就是说

system(("open "s + url).c_str()); // c++

system(("open "s + url).c_str()); // c++

https://linux.die.net/man/1/open

https://linux.die.net/man/1/open

回答by u7109869

I was having the exact same problem in Windows.

我在 Windows 中遇到了完全相同的问题。

I noticed that in OP's gist, he uses string("open ")in line 21, however, by using it one comes across this error:

我注意到在OP 的 gist 中,他string("open ")在第 21 行使用,但是,通过使用它会遇到此错误:

'open' is not recognized as an internal or external command

'open' 不被识别为内部或外部命令

After researching, I have found that openis MacOS the default command to open things. It is different on Windows or Linux.

经过研究,我发现openMacOS 是打开东西的默认命令。在 Windows 或 Linux 上是不同的。

Linux: xdg-open <URL>

Linuxxdg-open <URL>

Windows: start <URL>

窗户start <URL>



For those of you that are using Windows, as I am, you can use the following:

对于像我一样使用 Windows 的人,您可以使用以下内容:

std::string op = std::string("start ").append(url);
system(op.c_str());

回答by yhu420

For linux environments, you can use xdg-open. It is installed by default on most distributions. The benefit over the accepted answer is that it opens the user's preferred browser.

对于 linux 环境,您可以使用xdg-open. 它默认安装在大多数发行版上。接受答案的好处是它打开了用户的首选浏览器。

$ xdg-open https://google.com
$ xdg-open steam://run/10

Of course you can wrap this in a system()call.

当然,您可以将其封装在system()调用中。

回答by invadev

Create a function and copy the code using winsock which is mentioned already by Software_Developer.

创建一个函数并使用Software_Developer 已经提到的winsock 复制代码。

For Instance:

例如:

#ifdef _WIN32

// this is required only for windows

if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0)
{

  //...

}

#endif

winsock code here

winsock 代码在这里

#ifdef _WIN32

WSACleanup();

#endif