2015-04-07 23 views
0

我想编写一个代码连接我们的本地服务器,登录到该网页并检索一些数据。我可以使用服务器IP和连接功能连接服务器。现在我需要登录上接受以下格式的网页:使用套接字编程登录到服务器

addUPI?function=login&user=user-name&passwd=user-password&host-id=xxxx&mode=t/z

我写了这样的事情:

int ret= send(sock,"addUPI?funcion...&mode=t",strlen("addUPI?funcion...&mode=t"),0); 

,但它不工作。有人可以帮我吗?

+1

你真的不想要连接到使用原始套接字服务器。寻找一个为您的平台实现HTTP客户端的库。你在用什么语言? – PaulProgrammer

+0

我正在使用C++。 – user4760810

+0

试试[cURL库](http://curl.haxx.se/libcurl/cplusplus/)。 – PaulProgrammer

回答

0

这不是真的做HTTP的正确方法。一方面,典型的HTTP生命周期看起来是这样的(非常略):

...Connect 
>>> GET/HTTP/1.0 
>>> Host: localhost 
>>> Referrer: http://www.google.com 
>>> 
<<< HTTP/1.0 200 OK 
<<< Date: Wed, 08 Apr 2015 05:21:32 GMT 
<<< Content-Type: text/html 
<<< Content-Length: 20 
<<< Set-Cookie: ... 
<<< 
<<< <html><h1>Hello World</h1></html> 

,这就是假设没有重定向,SSL或其他神秘的协议发生的事情。所以,只写上面指定的字符串会导致关闭的连接,因为没有遵循协议。

真的,您可能想要使用完全烘焙的HTTP库,如cURL,它管理所有协议要求。

我无耻地改编自curl website这个例子:

#include <stdio.h> 
#include <curl/curl.h> 

int main(void) 
{ 
    CURL *curl; 
    CURLcode res; 

    curl = curl_easy_init(); 
    if(curl) { 
    curl_easy_setopt(curl, CURLOPT_URL, "http://example.com/addUPI?function=login&user=user-name&passwd=user-password&host-id=xxxx&mode=t"); 
    /* example.com is redirected, so we tell libcurl to follow redirection */ 
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); 

    /* Perform the request, res will get the return code */ 
    res = curl_easy_perform(curl); 
    /* Check for errors */ 
    if(res != CURLE_OK) 
     fprintf(stderr, "curl_easy_perform() failed: %s\n", 
       curl_easy_strerror(res)); 

    /* always cleanup */ 
    curl_easy_cleanup(curl); 
    } 
    return 0; 
}