The Artima Developer Community
Sponsored Link

Java Answers Forum
Let's try again...

2 replies on 1 page. Most recent reply: Nov 19, 2002 9:53 AM by Eduardo

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 2 replies on 1 page
Eduardo

Posts: 21
Nickname: eduardo
Registered: Feb, 2002

Let's try again... Posted: Nov 15, 2002 6:56 AM
Reply to this message Reply
Advertisement
Well, I have to include a "User-Agent" line in this code down here. It has to identify this web client and it can be any name I want, but I didn't understand how to do that. Does anybody know????

Thank you!
public class HttpClient2 {
    public static void main(String[] args) {
        try {
            // Check the arguments
            if ((args.length != 1) && (args.length != 2))
                throw new IllegalArgumentException("Wrong number of args");
            
            // Get an output stream to write the URL contents to
            OutputStream to_file;
            if (args.length == 2) to_file = new FileOutputStream(args[1]);
            else to_file = System.out;
            
            // Now use the URL class to parse the user-specified URL into
            // its various parts.  
            URL url = new URL(args[0]);
            String protocol = url.getProtocol();
            if (!protocol.equals("http")) // Check that we support the protocol
               throw new IllegalArgumentException("Must use 'http:' protocol");
            String host = url.getHost();
            int port = url.getPort();
            if (port == -1) port = 80; // if no port, use the default HTTP port
            String filename = url.getFile();
 
            // Open a network socket connection to the specified host and port
            Socket socket = new Socket(host, port);
 
          
             // Get input and output streams for the socket (modified inspired in HTTPMirror)
                BufferedReader in = 
                	new BufferedReader(
			       		new InputStreamReader(
			       			socket.getInputStream()));
			       			
                PrintWriter out = new PrintWriter(socket.getOutputStream());
 
                // Send the HTTP GET command to the Web server, specifying the file
                // This uses a newer version from the HTTP protocol.
                
                out.print("GET " + filename + "\n"); 
                out.write(filename);    
                out.print("\n");                         // End 
                out.flush(); // Send it right now!
 
                // Now, read the HTTP request from the client, and send it
                // right back to the client as part of the body of our
                // response.  The client doesn't disconnect, so we never get
                // an EOF.  It does sends an empty line at the end of the
                // headers, though.  So when we see the empty line, we stop
                // reading.  This means we don't mirror the contents of POST
                // requests, for example.  Note that the readLine() method 
				// works with Unix, Windows, and Mac line terminators.
 
                String line;
                // this is the header reader
                while((line = in.readLine()) != null) {
                    if (line.length() == 0) break;
                    System.out.println(line + "\n");
                }
                
                // this is the GET reader
                while((line = in.readLine()) != null) {
                    if (line.length() == 0) break;
                    System.out.println(line + "\n");
                }
 
            
		
		socket.close();		// Close the socket itself
 
		in.close();      // Close the input stream
		to_file.close();     // Flush and close the output stream 
        }
        catch (Exception e) {    // Report any errors that arise
            System.err.println(e);
            System.err.println("Usage: java HttpClient2 <URL> [<filename>]");
        }
    }
}


Charles Bell

Posts: 519
Nickname: charles
Registered: Feb, 2002

Re: Let's try again... Posted: Nov 16, 2002 8:24 AM
Reply to this message Reply
The User-Agent is set in the http request.


import java.io.*;
import java.net.*;
import java.util.*;

public class HttpClient2 {
public static void main(String[] args) {
Socket socket = null;
try {
// Check the arguments
if ((args.length != 1) && (args.length != 2))
throw new IllegalArgumentException("Wrong number of args");

// Get an output stream to write the URL contents to
FileWriter fw = new FileWriter(args[1]);

// Now use the URL class to parse the user-specified URL into
// its various parts.
URL url = new URL(args[0]);
String protocol = url.getProtocol();
if (!protocol.equals("http")) // Check that we support the protocol
throw new IllegalArgumentException("Must use 'http:' protocol");
String html = "";
String resource = "/";
String headerString = "";
String host = url.getHost();
int httpPort = 80;
String userAgent = "";
System.out.println("Creating connection to " + host
+ " on port " + String.valueOf(httpPort) + ".");
socket = new Socket(host, httpPort);
//create connection
System.out.println("Created socket: " + socket.toString());

System.out.println("Setting up communications to and from the connection.");
PrintStream ps = new PrintStream(socket.getOutputStream());

String request = "TRACE " + resource + " HTTP/1.0\n";
request = request + "Hello: hey over there\n";
request = request + "User-Agent: Java Man From Mars\n";
request = request + "Host: host\n";
request = request + "Accept: text/html, image/gif, image/jpeg, /\n";
request = request + "Connection: close\n";

System.out.println("Sending HTTP request: " + request);
ps.println(request);
ps.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("Reading webpage header: " + host + resource);
//read up to blank line
String s = br.readLine();
fw.write(s + "\n");

while ((s = br.readLine()) != null && !s.equals("")){
headerString = headerString + s;
s = br.readLine();
System.out.println(s);
fw.write(s + "\n");
if (s.indexOf("User-Agent") >= 0){
System.out.println("Found User-Agent");
userAgent = s.substring(s.indexOf(":") + 1);
System.out.println("User-Agent: " + userAgent);
}
}
System.out.println("Reading webpage: " + host + resource);

s = br.readLine();
fw.write(s + "\n");
while((s = br.readLine()) != null){
html = html + s + "\n";
System.out.println(s);
fw.write(s + "\n");
if (s.indexOf("User-Agent") >= 0){
System.out.println("Found User-Agent");
userAgent = s.substring(s.indexOf(":") + 1);
System.out.println("User-Agent: " + userAgent);
}
}
fw.close();
}catch(MalformedURLException murle){
System.err.println("MalformedURLException: " + murle.getMessage());
}catch(UnknownHostException uhe){
System.err.println("UnknownHostException: " + uhe.getMessage());
}catch (ConnectException ce){
System.err.println("ConnectException: " + ce.getMessage());
}catch (IOException ioe){
System.err.println("IOException: " + ioe.getMessage());
}finally{
if (socket != null) {
try{
socket.close();
}catch (IOException ioe){
System.err.println("IOException: " + ioe.getMessage());
}
}
}
}
}

Eduardo

Posts: 21
Nickname: eduardo
Registered: Feb, 2002

Re: Let's try again... Posted: Nov 19, 2002 9:53 AM
Reply to this message Reply
Hi, Charles!

Thank you very much! I was researching in the wrong direction: looking for something like "setUserAgent", etc. So, you saved me from a long journey to nowhere! :O) I really appreciated that!

Eduardo

Flat View: This topic has 2 replies on 1 page
Topic: Can someone give me  an exsample?? Previous Topic   Next Topic Topic: can a file be uploaded automatically without

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use