Tag Archives: HTTP

Downloading a Web page in Java using a java.net.Socket

import java.io.*;
import java.net.*;
 
public class SocketHTTPClient {
    public static void main(String[] args) {
         
        String hostName = "www.martinbroadhurst.com";
        int portNumber = 80;
 
        try {
            Socket socket = new Socket(hostName, portNumber);
            PrintWriter out =
                new PrintWriter(socket.getOutputStream(), true);
            BufferedReader in =
                new BufferedReader(
                    new InputStreamReader(socket.getInputStream()));
            out.println("GET / HTTP/1.1\nHost: www.martinbroadhurst.com\n\n");
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
            }
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host " + hostName);
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to " +
                hostName);
            System.exit(1);
        } 
    }
}

Downloading a Web page in C using neon

#include <stdio.h>

#include <neon/ne_socket.h>
#include <neon/ne_session.h>
#include <neon/ne_request.h>

int main(void)
{
    ne_sock_init();	 
    ne_session *session = ne_session_create("http",	"www.martinbroadhurst.com", 80);
    ne_request *request = ne_request_create(session, "GET", "/");
    if (ne_begin_request(request) == NE_OK) {
        char buf[1024];
        size_t bytes_read;
        while ((bytes_read = ne_read_response_block(request, buf, 1024)) > 0) {
            printf("%.*s", (int)bytes_read, buf);
        }
        ne_end_request(request);
    }
    else {
        printf("Failed to dispatch request\n");
    }
    ne_request_destroy(request);
    ne_close_connection(session);
    ne_session_destroy(session);
    ne_sock_exit();	 
    return 0;
}

Reference: neon HTTP and WebDAV client library

Downloading a Web page in C using libcurl

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

size_t write(void *ptr, size_t size, size_t nmemb, void *stream)
{
	FILE *fptr = stream;
	return fwrite(ptr, size, nmemb, fptr); 
}	

int main(void)
{
	CURL *curl = curl_easy_init();
	FILE *fptr = fopen("index.html", "w+");
	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write);
	curl_easy_setopt(curl, CURLOPT_WRITEDATA, stdout);
	curl_easy_setopt(curl, CURLOPT_URL, "http://www.martinbroadhurst.com/");
	curl_easy_perform(curl);
	fclose(fptr);
	curl_easy_cleanup(curl);

	return 0;
}

Reference: libcurl – the multiprotocol file transfer library