如何用C语言编写简单的HTTP请求和响应。
在Java中我可以使用:
String url = "http://www.google.com/search?q=mkyong";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
我怎样才能使用C语言?
我已尝试Here: 但它没有正常工作。
主要回应:HTTP/1.1 301 Moved Permanently Location: http://www.google.co.in/ Content-Type: text/html; charset=UTF-8 Date: Mon, 27 Jun 2016 13:53:36 GMT Expires: Wed, 27 Jul 2016 13:53:36 GMT Cache-Control: public, max-age=2592000 Server: gws Content-Length: 221 X-XSS-Protection: 1; mode=block X-Frame-Options: SAMEORIGIN
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8"> <TITLE>301 Moved</TITLE></HEAD><BODY> <H1>301 Moved</H1> The document has moved <A HREF="http://www.google.co.in/">here</A>. </BODY></HTML>
答案 0 :(得分:1)
您需要一个外部库来解决您的问题,libcurl
是一个很好的选择。
试试这段(测试过的)代码:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <curl/curl.h>
typedef struct string_buffer_s
{
char * ptr;
size_t len;
} string_buffer_t;
static void string_buffer_initialize( string_buffer_t * sb )
{
sb->len = 0;
sb->ptr = malloc(sb->len+1);
sb->ptr[0] = '\0';
}
static void string_buffer_finish( string_buffer_t * sb )
{
free(sb->ptr);
sb->len = 0;
sb->ptr = NULL;
}
static size_t string_buffer_callback( void * buf, size_t size, size_t nmemb, void * data )
{
string_buffer_t * sb = data;
size_t new_len = sb->len + size * nmemb;
sb->ptr = realloc( sb->ptr, new_len + 1 );
memcpy( sb->ptr + sb->len, buf, size * nmemb );
sb->ptr[ new_len ] = '\0';
sb->len = new_len;
return size * nmemb;
}
static size_t header_callback(char * buf, size_t size, size_t nmemb, void * data )
{
return string_buffer_callback( buf, size, nmemb, data );
}
static size_t write_callback( void * buf, size_t size, size_t nmemb, void * data )
{
return string_buffer_callback( buf, size, nmemb, data );
}
int main( int argc, char * argv[] )
{
CURL * curl;
CURLcode res;
string_buffer_t strbuf;
char * myurl = argv[1];
string_buffer_initialize( &strbuf );
curl = curl_easy_init();
if(!curl)
{
fprintf(stderr, "Fatal: curl_easy_init() error.\n");
string_buffer_finish( &strbuf );
return EXIT_FAILURE;
}
curl_easy_setopt(curl, CURLOPT_URL, myurl );
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L );
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback );
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, header_callback );
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &strbuf );
curl_easy_setopt(curl, CURLOPT_HEADERDATA, &strbuf );
res = curl_easy_perform(curl);
if( res != CURLE_OK )
{
fprintf( stderr, "Request failed: curl_easy_perform(): %s\n", curl_easy_strerror(res) );
curl_easy_cleanup( curl );
string_buffer_finish( &strbuf );
return EXIT_FAILURE;
}
printf( "%s\n\n", strbuf.ptr );
curl_easy_cleanup( curl );
string_buffer_finish( &strbuf );
return EXIT_SUCCESS;
}
/* eof */
编译(gcc / linux):
$ gcc -Wall httpget.c -lcurl -o httpget
测试:
$ ./httpget "http://www.google.com/search?q=mkyong"
输出:
HTTP/1.1 302 Moved Temporarily
Location: http://ipv4.google.com/sorry/IndexRedirect?continue=http://www.google.com/search%3Fq%3Dmkyong%26safe%3Dactive&q=CGMSBL0cgPIYq_vEuwUiGQDxp4NLKiIBT1ZvF-YL0aR4jC6o1OrjEvE
Date: Mon, 27 Jun 2016 14:52:27 GMT
Pragma: no-cache
Expires: Fri, 01 Jan 1990 00:00:00 GMT
Cache-Control: no-store, no-cache, must-revalidate
Content-Type: text/html; charset=UTF-8
Server: HTTP server (unknown)
Content-Length: 368
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
X-Cache: MISS from proxy.foobar.com
X-Cache-Lookup: MISS from proxy.foobar.com:80
Via: 1.1 proxy.foobar.com (squid)
Connection: keep-alive
HTTP/1.1 503 Service Unavailable
Date: Mon, 27 Jun 2016 14:52:27 GMT
Pragma: no-cache
Expires: Fri, 01 Jan 1990 00:00:00 GMT
Cache-Control: no-store, no-cache, must-revalidate
Content-Type: text/html
Server: HTTP server (unknown)
Content-Length: 2924
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
X-Cache: MISS from proxy.foobar.com
X-Cache-Lookup: MISS from proxy.foobar.com:80
Via: 1.1 proxy.foobar.com (squid)
Connection: keep-alive
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head><meta http-equiv="content-type" content="text/html; charset=utf-8"><meta name="viewport" content="initial-scale=1"><title>http://www.google.com/search?q=mkyong&safe=active</title></head>
<body style="font-family: arial, sans-serif; background-color: #fff; color: #000; padding:20px; font-size:18px;" onload="e=document.getElementById('captcha');if(e){e.focus();}">
<div style="max-width:400px;">
<hr noshade size="1" style="color:#ccc; background-color:#ccc;"><br>
To continue, please type the characters below:<br><br>
<img src="/sorry/image?id=12134302468701323331&q=CGMSBL0cgPIYq_vEuwUiGQDxp4NLKiIBT1ZvF-YL0aR4jC6o1OrjEvE&hl=en&continue=http://www.google.com/search%3Fq%3Dmkyong%26safe%3Dactive" border="1" alt="Please enable images"><br><br><form action="CaptchaRedirect" method="get"><input type='hidden' name='q' value='CGMSBL0cgPIYq_vEuwUiGQDxp4NLKiIBT1ZvF-YL0aR4jC6o1OrjEvE'><input type="hidden" name="continue" value="http://www.google.com/search?q=mkyong&safe=active"><input type="hidden" name="id" value="12134302468701323331"><input type="text" name="captcha" value="" id="captcha" size="12" style="font-size:16px; padding:3px 0 3px 5px; margin-left:0px;"><input type="submit" name="submit" value="Submit" style="font-size:18px; padding:4px 0;"><br><br><br></form>
<hr noshade size="1" style="color:#ccc; background-color:#ccc;">
<div style="font-size:13px;">
<b>About this page</b><br><br>Our systems have detected unusual traffic from your computer network. This page checks to see if it's really you sending the requests, and not a robot. <a href="#" onclick="document.getElementById('infoDiv').style.display='block';">Why did this happen?</a><br><br>
<div id="infoDiv" style="display:none; background-color:#eee; padding:10px; margin:0 0 15px 0; line-height:1.4em;">
This page appears when Google automatically detects requests coming from your computer network which appear to be in violation of the <a href="//www.google.com/policies/terms/">Terms of Service</a>. The block will expire shortly after those requests stop. In the meantime, solving the above CAPTCHA will let you continue to use our services.<br><br>This traffic may have been sent by malicious software, a browser plug-in, or a script that sends automated requests. If you share your network connection, ask your administrator for help — a different computer using the same IP address may be responsible. <a href="//support.google.com/websearch/answer/86640">Learn more</a><br><br>Sometimes you may be asked to solve the CAPTCHA if you are using advanced terms that robots are known to use, or sending requests very quickly.
</div>
IP address: 189.28.128.242<br>Time: 2016-06-27T14:52:27Z<br>URL: http://www.google.com/search?q=mkyong&safe=active<br>
</div>
</div>
</body>
</html>
希望它有所帮助!