HTTP Request

From Rosetta Code

Jump to: navigation, search

Programming Task
This is a programming task. It lays out a problem which Rosetta Code users are encouraged to solve, using languages they know.

Code examples should be formatted along the lines of one of the existing prototypes.

Print a URL's content (source code) to the console.

Contents

[edit] C#

Not tested.

using System;
using System.Net;
using System.Text;

class Program
{
  static void Main()
  {
    string url = "http://www.rosettacode.org/";
    WebClient wc = new WebClient();
    byte[] data = wc.DownloadData(url);
    string content = Encoding.UTF8.GetString(data);
    Console.WriteLine(content);
  }
}

[edit] Erlang

[edit] Synchronous

-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.

[edit] Asynchronous

-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.

Using it

|escript ./req.erl http://www.rosettacode.org

[edit] Java

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

Apache Commons IO

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

[edit] Perl

using LWP::Simple;
print get("http://www.rosettacode.org");

[edit] PHP

print(file_get_contents("http://www.rosettacode.org"));

[edit] Python

import urllib
url = urllib.urlopen("http://www.rosettacode.org")
print url.read()
url.close()
import urllib
print urllib.urlopen("http://rosettacode.org").read()

[edit] Ruby

require 'open-uri'
require 'kconv'
 
puts open("http://rosettacode.org").read

[edit] Tcl

package require http
set request [http::geturl "http://www.rosettacode.org"]
puts [http::data $request]
Personal tools