This commit is contained in:
Ingy döt Net 2013-04-10 21:29:02 -07:00
parent 764da6cbbb
commit db842d013d
19005 changed files with 197040 additions and 7 deletions

2
Task/HTTP/0DESCRIPTION Normal file
View file

@ -0,0 +1,2 @@
Access and print a [[wp:Uniform Resource Locator|URL's]] content (the located resource) to the console.
There is a separate task for [[HTTPS Request]]s.

4
Task/HTTP/1META.yaml Normal file
View file

@ -0,0 +1,4 @@
---
category:
- Networking and Web Interaction
note: Programming environment operations

View file

@ -0,0 +1,29 @@
STRING domain="rosettacode.org";
STRING page="wiki/Main_Page";
STRING re success="^HTTP/[0-9.]* 200";
STRING re result description="^HTTP/[0-9.]* [0-9]+ [a-zA-Z ]*";
STRING re doctype ="\s\s<!DOCTYPE html PUBLIC ""[^>]+"">\s+";
PROC html page = (REF STRING page) BOOL: (
BOOL out=grep in string(re success, page, NIL, NIL) = 0;
IF INT start, end;
grep in string(re result description, page, start, end) = 0
THEN
page:=page[end+1:];
IF grep in string(re doctype, page, start, end) = 0
THEN page:=page[start+2:]
ELSE print ("unknown format retrieving page")
FI
ELSE print ("unknown error retrieving page")
FI;
out
);
IF STRING reply;
INT rc =
http content (reply, domain, "http://"+domain+"/"+page, 0);
rc = 0 AND html page (reply)
THEN print (reply)
ELSE print (strerror (rc))
FI

View file

@ -0,0 +1,21 @@
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.net.*;
public class RequestExample extends Sprite
{
public function RequestExample()
{
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, loadComplete);
loader.load(new URLRequest("http://www.rosettacode.org"));
}
private function loadComplete(evt:Event):void
{
trace(evt.target.data);
}
}
}

9
Task/HTTP/Ada/http.ada Normal file
View file

@ -0,0 +1,9 @@
with Ada.Text_IO; use Ada.Text_IO;
with AWS.Client;
with AWS.Response;
procedure HTTP_Request is
begin
Put_Line (AWS.Response.Message_Body (AWS.Client.Get (URL => "http://www.rosettacode.org")));
end HTTP_Request;

View file

@ -0,0 +1,2 @@
UrlDownloadToFile, http://rosettacode.org, url.html
Run, cmd /k type url.html

View file

@ -0,0 +1,9 @@
SYS "LoadLibrary", "URLMON.DLL" TO urlmon%
SYS "GetProcAddress", urlmon%, "URLDownloadToFileA" TO URLDownloadToFile
url$ = "http://www.bbcbasic.co.uk/aboutus.html"
file$ = @tmp$ + "rosetta.tmp"
SYS URLDownloadToFile, 0, url$, file$, 0, 0 TO fail%
IF fail% ERROR 100, "File download failed"
OSCLI "TYPE """ + file$ + """"

View file

@ -0,0 +1 @@
curl.exe -s -L http://rosettacode.org/

View file

@ -0,0 +1 @@
$httpExt.ExecRemote("www.tabasoft.it")

38
Task/HTTP/C++/http-1.cpp Normal file
View file

@ -0,0 +1,38 @@
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iostream>
int main() {
WSADATA wsaData;
WSAStartup( MAKEWORD( 2, 2 ), &wsaData );
addrinfo *result = NULL;
addrinfo hints;
ZeroMemory( &hints, sizeof( hints ) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
getaddrinfo( "74.125.45.100", "80", &hints, &result ); // http://www.google.com
SOCKET s = socket( result->ai_family, result->ai_socktype, result->ai_protocol );
connect( s, result->ai_addr, (int)result->ai_addrlen );
freeaddrinfo( result );
send( s, "GET / HTTP/1.0\n\n", 16, 0 );
char buffer[512];
int bytes;
do {
bytes = recv( s, buffer, 512, 0 );
if ( bytes > 0 )
std::cout.write(buffer, bytes);
} while ( bytes > 0 );
return 0;
}

8
Task/HTTP/C++/http-2.cpp Normal file
View file

@ -0,0 +1,8 @@
#include <Web/Web.h>
using namespace Upp;
CONSOLE_APP_MAIN
{
Cout() << HttpClient("www.rosettacode.org").ExecuteRedirect();
}

13
Task/HTTP/C-sharp/http.cs Normal file
View file

@ -0,0 +1,13 @@
using System;
using System.Text;
using System.Net;
class Program
{
static void Main(string[] args)
{
WebClient wc = new WebClient();
string content = wc.DownloadString("http://www.google.com");
Console.WriteLine(content);
}
}

22
Task/HTTP/C/http.c Normal file
View file

@ -0,0 +1,22 @@
#include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>
int
main(void)
{
CURL *curl;
char buffer[CURL_ERROR_SIZE];
if ((curl = curl_easy_init()) != NULL) {
curl_easy_setopt(curl, CURLOPT_URL, "http://www.rosettacode.org/");
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, buffer);
if (curl_easy_perform(curl) != CURLE_OK) {
fprintf(stderr, "%s\n", buffer);
return EXIT_FAILURE;
}
curl_easy_cleanup(curl);
}
return EXIT_SUCCESS;
}

View file

@ -0,0 +1,6 @@
(defn get-http [url]
(let [sc (java.util.Scanner.
(.openStream (java.net.URL. url)))]
(while (.hasNext sc)
(println (.nextLine sc)))))
(get-http "http://www.rosettacode.org")

View file

@ -0,0 +1,4 @@
(ns example
(:use [clojure.contrib.http.agent :only (string http-agent)]))
(println (string (http-agent "http://www.rosettacode.org/")))

View file

@ -0,0 +1 @@
(print (slurp "http://www.rosettacode.org/"))

View file

@ -0,0 +1,2 @@
<cfhttp url="http://www.rosettacode.org" result="result">
<cfoutput>#result.FileContent#</cfoutput>

View file

@ -0,0 +1,5 @@
(defun wget-clisp (url)
(ext:with-http-input (stream url)
(loop for line = (read-line stream nil nil)
while line
do (format t "~a~%" line))))

View file

@ -0,0 +1,10 @@
(defun wget-drakma-string (url &optional (out *standard-output*))
"Grab the body as a string, and write it to out."
(write-string (drakma:http-request url) out))
(defun wget-drakma-stream (url &optional (out *standard-output*))
"Grab the body as a stream, and write it to out."
(loop with body = (drakma:http-request url :want-stream t)
for line = (read-line body nil nil)
while line do (write-line line out)
finally (close body)))

4
Task/HTTP/D/http-1.d Normal file
View file

@ -0,0 +1,4 @@
void main() {
import std.stdio, std.net.curl;
writeln(get("http://google.com"));
}

6
Task/HTTP/D/http-2.d Normal file
View file

@ -0,0 +1,6 @@
import tango.io.Console;
import tango.net.http.HttpGet;
void main() {
Cout.stream.copy( (new HttpGet("http://google.com")).open );
}

10
Task/HTTP/D/http-3.d Normal file
View file

@ -0,0 +1,10 @@
import tango.io.Console;
import tango.net.InternetAddress;
import tango.net.device.Socket;
void main() {
auto site = new Socket;
site.connect (new InternetAddress("google.com",80)).write ("GET / HTTP/1.0\n\n");
Cout.stream.copy (site);
}

View file

@ -0,0 +1,43 @@
program HTTP;
{$APPTYPE CONSOLE}
{$DEFINE DEBUG}
uses
Classes,
httpsend; // Synapse httpsend class
var
Response: TStrings;
HTTPObj: THTTPSend;
begin
HTTPObj := THTTPSend.Create;
try
{ Stringlist object to capture HTML returned
from URL }
Response := TStringList.Create;
try
if HTTPObj.HTTPMethod('GET','http://www.mgis.uk.com') then
begin
{ Load HTTP Document into Stringlist }
Response.LoadFromStream(HTTPObj.Document);
{ Write the response to the console window }
Writeln(Response.Text);
end
else
Writeln('Error retrieving data');
finally
Response.Free;
end;
finally
HTTPObj.Free;
end;
// Keep console window open
Readln;
end.

View file

@ -0,0 +1,19 @@
program ShowHTTP;
{$APPTYPE CONSOLE}
uses IdHttp;
var
s: string;
lHTTP: TIdHTTP;
begin
lHTTP := TIdHTTP.Create(nil);
try
lHTTP.HandleRedirects := True;
s := lHTTP.Get('http://www.rosettacode.org');
Writeln(s);
finally
lHTTP.Free;
end;
end.

3
Task/HTTP/E/http.e Normal file
View file

@ -0,0 +1,3 @@
when (def t := <http://www.rosettacode.org> <- getText()) -> {
println(t)
}

View file

@ -0,0 +1,9 @@
-module(main).
-export([main/1]).
main([Url|[]]) ->
inets:start(),
case http:request(Url) of
{ok, {_V, _H, Body}} -> io:fwrite("~p~n",[Body]);
{error, Res} -> io:fwrite("~p~n", [Res])
end.

View file

@ -0,0 +1,11 @@
-module(main).
-export([main/1]).
main([Url|[]]) ->
inets:start(),
http:request(get, {Url, [] }, [], [{sync, false}]),
receive
{http, {_ReqId, Res}} -> io:fwrite("~p~n",[Res]);
_Any -> io:fwrite("Error: ~p~n",[_Any])
after 10000 -> io:fwrite("Timed out.~n",[])
end.

View file

@ -0,0 +1 @@
|escript ./req.erl http://www.rosettacode.org

View file

@ -0,0 +1,2 @@
USE: http.client
"http://www.rosettacode.org" http-get nip print

6
Task/HTTP/Forth/http.fth Normal file
View file

@ -0,0 +1,6 @@
include unix/socket.fs
s" localhost" 80 open-socket
dup s\" GET / HTTP/1.0\n\n" rot write-socket
dup pad 8092 read-socket type
close-socket

View file

@ -0,0 +1,3 @@
Start,Programs,Applications,Mozilla Firefox,Inputbox:address bar>www.rosettacode.org,Button:Go,
Click:Area:browser window,Type:[Control A],[Control C],Start,Programs,Accessories,Notepad,
Menu:Edit,Paste

16
Task/HTTP/Go/http.go Normal file
View file

@ -0,0 +1,16 @@
package main
import (
"io"
"log"
"net/http"
"os"
)
func main() {
r, err := http.Get("http://rosettacode.org/robots.txt")
if err != nil {
log.Fatalln(err)
}
io.Copy(os.Stdout, r.Body)
}

View file

@ -0,0 +1 @@
new URL("http://www.rosettacode.org").eachLine { println it }

View file

@ -0,0 +1,11 @@
import Network.Browser
import Network.HTTP
import Network.URI
httpreq = do
rsp <- Network.Browser.browse $ do
setAllowRedirects True
setOutHandler $ const (return ())
request $ getRequest "http://www.rosettacode.org/"
putStrLn $ rspBody $ snd rsp

View file

@ -0,0 +1,19 @@
link cfunc
procedure main(arglist)
get(arglist[1])
end
procedure get(url)
local f, host, port, path
url ? {
="http://" | ="HTTP://"
host := tab(upto(':/') | 0)
if not (=":" & (port := integer(tab(upto('/'))))) then port := 80
if pos(0) then path := "/" else path := tab(0)
}
write(host)
write(path)
f := tconnect(host, port) | stop("Unable to connect")
writes(f, "GET ", path | "/" ," HTTP/1.0\r\n\r\n")
while write(read(f))
end

View file

@ -0,0 +1 @@
|icon req.icn http://www.rosettacode.org

View file

@ -0,0 +1,4 @@
procedure main(arglist)
m := open(arglist[1],"m")
while write(read(m))
end

1
Task/HTTP/J/http.j Normal file
View file

@ -0,0 +1 @@
gethttp 'http://www.rosettacode.org'

View file

@ -0,0 +1,10 @@
import java.util.Scanner;
import java.net.URL;
public class Main {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(new URL("http://www.rosettacode.org").openStream());
while (sc.hasNext())
System.out.println(sc.nextLine());
}
}

View file

@ -0,0 +1,8 @@
import org.apache.commons.io.IOUtils;
import java.net.URL;
public class Main {
public static void main(String[] args) throws Exception {
IOUtils.copy(new URL("http://rosettacode.org").openStream(),System.out);
}
}

20
Task/HTTP/LSL/http.lsl Normal file
View file

@ -0,0 +1,20 @@
string sURL = "http://www.RosettaCode.Org";
key kHttpRequestId;
default {
state_entry() {
kHttpRequestId = llHTTPRequest(sURL, [], "");
}
http_response(key kRequestId, integer iStatus, list lMetaData, string sBody) {
if(kRequestId==kHttpRequestId) {
llOwnerSay("Status="+(string)iStatus);
integer x = 0;
for(x=0 ; x<llGetListLength(lMetaData) ; x++) {
llOwnerSay("llList2String(lMetaData, "+(string)x+")="+llList2String(lMetaData, x));
}
list lBody = llParseString2List(sBody, ["\n"], []);
for(x=0 ; x<llGetListLength(lBody) ; x++) {
llOwnerSay("llList2String(lBody, "+(string)x+")="+llList2String(lBody, x));
}
}
}
}

View file

@ -0,0 +1,20 @@
result = DownloadToFile( "http://rosettacode.org/wiki/Main_Page", "in.html")
timer 2000, [on]
wait
[on]
timer 0
if result <> 0 then print "Error downloading."
end
Function DownloadToFile( urlfile$, localfile$)
open "URLmon" for dll as #url
calldll #url, "URLDownloadToFileA",_
0 as long,_ 'null
urlfile$ as ptr,_ 'url to download
localfile$ as ptr,_ 'save file name
0 as long,_ 'reserved, must be 0
0 as long,_ 'callback address, can be 0
DownloadToFile as ulong '0=success
close #url
end function

20
Task/HTTP/Lua/http.lua Normal file
View file

@ -0,0 +1,20 @@
local http = require("socket.http")
function url_encode(str)
if (str) then
str = string.gsub (str, "\n", "\r\n")
str = string.gsub (str, "([^%w ])",
function (c) return string.format ("%%%02X", string.byte(c)) end)
str = string.gsub (str, " ", "+")
end
return str
end
function url_decode(str)
str = string.gsub (str, "+", " ")
str = string.gsub (str, "%%(%x%x)",
function(h) return string.char(tonumber(h,16)) end)
str = string.gsub (str, "\r\n", "\n")
return str
end
local page = http.request( 'http://www.google.com/m/search?q=' .. url_encode("lua") )
print( page )

5
Task/HTTP/MATLAB/http.m Normal file
View file

@ -0,0 +1,5 @@
>> random = urlread('http://www.random.org/integers/?num=1&min=1&max=100&col=1&base=10&format=plain&rnd=new')
random =
61

View file

@ -0,0 +1 @@
HTTP:-Get( "http://www.google.com" );

View file

@ -0,0 +1 @@
Print[Import["http://www.google.com/webhp?complete=1&hl=en", "Source"]]

1
Task/HTTP/PHP/http.php Normal file
View file

@ -0,0 +1 @@
readfile("http://www.rosettacode.org");

2
Task/HTTP/Perl/http-1.pl Normal file
View file

@ -0,0 +1,2 @@
use LWP::Simple;
print get("http://www.rosettacode.org");

9
Task/HTTP/Perl/http-2.pl Normal file
View file

@ -0,0 +1,9 @@
use strict;
use LWP::UserAgent;
my $url = 'http://www.rosettacode.org';
my $response = LWP::UserAgent->new->get( $url );
$response->is_success or die "Failed to GET '$url': ", $response->status_line;
print $response->as_string;

View file

@ -0,0 +1,4 @@
(load "@lib/http.l")
(client "rosettacode.org" 80 NIL # Connect to rosettacode
(out NIL (echo)) ) # Echo to standard output

View file

@ -0,0 +1,6 @@
:- use_module(library( http/http_open )).
http :-
http_open('http://www.rosettacode.org/',In, []),
copy_stream_data(In, user_output),
close(In).

View file

@ -0,0 +1,2 @@
import urllib.request
print(urllib.request.urlopen("http://rosettacode.org").read())

View file

@ -0,0 +1,2 @@
import urllib
print urllib.urlopen("http://rosettacode.org").read()

View file

@ -0,0 +1,2 @@
import urllib2
print urllib2.urlopen("http://rosettacode.org").read()

10
Task/HTTP/R/http-1.r Normal file
View file

@ -0,0 +1,10 @@
library(RCurl)
webpage <- getURL("http://rosettacode.org")
#If you are linking to a page that no longer exists and need to follow the redirect, use followlocation=TRUE
webpage <- getURL("http://www.rosettacode.org", .opts=list(followlocation=TRUE))
#If you are behind a proxy server, you will need to use something like:
webpage <- getURL("http://rosettacode.org",
.opts=list(proxy="123.123.123.123", proxyusername="domain\\username", proxypassword="mypassword", proxyport=8080))
#Don't forget that backslashes in your username or password need to be escaped!

3
Task/HTTP/R/http-2.r Normal file
View file

@ -0,0 +1,3 @@
library(XML)
pagetree <- htmlTreeParse(webpage )
pagetree$children$html

View file

@ -0,0 +1,5 @@
#lang racket
(require net/url)
(copy-port (get-pure-port (string->url "http://www.rosettacode.org")
#:redirections 100)
(current-output-port))

3
Task/HTTP/Ruby/http-1.rb Normal file
View file

@ -0,0 +1,3 @@
require 'open-uri'
print open("http://rosettacode.org") {|f| f.read}

4
Task/HTTP/Ruby/http-2.rb Normal file
View file

@ -0,0 +1,4 @@
require 'fileutils'
require 'open-uri'
open("http://rosettacode.org/") {|f| FileUtils.copy_stream(f, $stdout)}

View file

@ -0,0 +1,12 @@
import scala.io._
object HttpTest {
def main(args: Array[String]): Unit = {
//if you are behind a firewall you can configure your proxy
System.setProperty("http.proxySet", "true")
System.setProperty("http.proxyHost", "0.0.0.0")
System.setProperty("http.proxyPort", "8080")
Source.fromURL("http://www.rosettacode.org").getLines.foreach(println)
}
}

26
Task/HTTP/Scheme/http.ss Normal file
View file

@ -0,0 +1,26 @@
; Use the regular expression module to parse the url (included with Guile)
(use-modules (ice-9 regex))
; Set the url and parse the hostname, port, and path into variables
(define url "http://www.rosettacode.org/wiki/HTTP")
(define r (make-regexp "^(http://)?([^:/]+)(:)?(([0-9])+)?(/.*)?" regexp/icase))
(define host (match:substring (regexp-exec r url) 2))
(define port (match:substring (regexp-exec r url) 4))
(define path (match:substring (regexp-exec r url) 6))
; Set port to 80 if it wasn't set above and convert from a string to a number
(if (eq? port #f) (define port "80"))
(define port (string->number port))
; Connect to remote host on specified port
(let ((s (socket PF_INET SOCK_STREAM 0)))
(connect s AF_INET (car (hostent:addr-list (gethostbyname host))) port)
; Send a HTTP request for the specified path
(display "GET " s)
(display path s)
(display " HTTP/1.0\r\n\r\n" s)
; Display the received HTML
(do ((c (read-char s) (read-char s))) ((eof-object? c))
(display c)))

View file

@ -0,0 +1 @@
Transcript show: 'http://rosettacode.org' asUrl retrieveContents contentStream.

4
Task/HTTP/Tcl/http.tcl Normal file
View file

@ -0,0 +1,4 @@
package require http
set request [http::geturl "http://www.rosettacode.org"]
puts [http::data $request]
http::cleanup $request