/[classpath]/classpath/gnu/java/net/protocol/http/HttpURLConnection.java
ViewVC logotype

Diff of /classpath/gnu/java/net/protocol/http/HttpURLConnection.java

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.5 by iproetel, Mon Aug 11 13:59:14 2003 UTC revision 1.6 by mkoch, Sat Oct 18 09:49:52 2003 UTC
# Line 1  Line 1 
1  /* HttpURLConnection.java -- URLConnection class for HTTP protocol  /* HttpURLConnection.java -- URLConnection class for HTTP protocol
2     Copyright (C) 1998, 2002 Free Software Foundation, Inc.     Copyright (C) 1998, 2002, 2003 Free Software Foundation, Inc.
3    
4  This file is part of GNU Classpath.  This file is part of GNU Classpath.
5    
# Line 53  import java.io.PrintWriter; Line 53  import java.io.PrintWriter;
53  import java.io.IOException;  import java.io.IOException;
54  import java.util.Iterator;  import java.util.Iterator;
55  import java.util.Map;  import java.util.Map;
56    import gnu.java.net.HeaderFieldHelper;
57    
58  /**  /**
59    * This subclass of java.net.URLConnection models a URLConnection via   * This subclass of java.net.URLConnection models a URLConnection via
60    * the HTTP protocol.   * the HTTP protocol.
61    *   *
62    * @version 0.1   * @author Aaron M. Renn (arenn@urbanophile.com)
   *  
   * @author Aaron M. Renn (arenn@urbanophile.com)  
   */  
 public class HttpURLConnection extends java.net.HttpURLConnection  
 {  
   
 /*************************************************************************/  
   
 /*  
  * Instance Variables  
  */  
   
 /**  
   * The socket we are connected to  
   */  
 private Socket socket;  
   
 /**  
   * The InputStream for this connection  
   */  
 private DataInputStream in_stream;  
   
 /**  
   * The OutputStream for this connection  
   */  
 private OutputStream out_stream;  
   
 /**  
   * buffered_out_stream is a buffer to contain content of the HTTP request,  
   * and will be written to out_stream all at once  
   */  
 private ByteArrayOutputStream buffered_out_stream;  
   
 /**  
   * The PrintWriter for this connection (used internally)  
   */  
 private PrintWriter out_writer;  
   
 /**  
   * This is the object that holds the header field information  
   */  
 private gnu.java.net.HeaderFieldHelper headers =  
     new gnu.java.net.HeaderFieldHelper();  
   
 /*************************************************************************/  
   
 /*  
  * Constructors  
  */  
   
 /**  
   * Calls superclass constructor to initialize  
   */  
 protected  
 HttpURLConnection(URL url)  
 {  
   super(url);  
   
   /* Set up some variables */  
   doOutput = false;  
 }  
   
 /*************************************************************************/  
   
 /*  
  * Instance Methods  
63   */   */
64    public class HttpURLConnection extends java.net.HttpURLConnection
 /**  
   * Connects to the remote host, sends the request, and parses the reply  
   * code and header information returned  
   */  
 public void  
 connect() throws IOException  
 {  
   // Connect up  
   if (url.getPort() == -1)  
     socket = new Socket(url.getHost(), 80);  
   else  
     socket = new Socket(url.getHost(), url.getPort());  
   
   out_stream = new BufferedOutputStream(socket.getOutputStream());  
   out_writer = new PrintWriter(new OutputStreamWriter(out_stream, "8859_1"));  
   
   connected = true;  
 }  
   
 /**  
   * write HTTP request header and content to out_writer  
   */  
 void SendRequest() throws IOException  
65  {  {
66    // Send the request    /**
67    out_writer.print(getRequestMethod() + " " + getURL().getFile() +     * The socket we are connected to
68                     " HTTP/1.1\r\n");     */
69      private Socket socket;
70    
71      /**
72       * The InputStream for this connection
73       */
74      private DataInputStream in_stream;
75    
76      /**
77       * The OutputStream for this connection
78       */
79      private OutputStream out_stream;
80    
81      /**
82       * buffered_out_stream is a buffer to contain content of the HTTP request,
83       * and will be written to out_stream all at once
84       */
85      private ByteArrayOutputStream buffered_out_stream;
86    
87      /**
88       * The PrintWriter for this connection (used internally)
89       */
90      private PrintWriter out_writer;
91    
92      /**
93       * This is the object that holds the header field information
94       */
95      private HeaderFieldHelper headers = new HeaderFieldHelper();
96    
97      /**
98       * Calls superclass constructor to initialize
99       */
100      protected HttpURLConnection (URL url)
101      {
102        super (url);
103    
104    if (getRequestProperty("host") == null){      /* Set up some variables */
105      setRequestProperty("Host", getURL().getHost());      doOutput = false;
   }  
   if (getRequestProperty("Connection") == null){  
     setRequestProperty("Connection", "Close");  
   }  
   if (getRequestProperty("user-agent") == null){  
     setRequestProperty("user-agent",  
                 "gnu-classpath/" + System.getProperty("classpath.version"));  
   }  
   if (getRequestProperty("accept") == null){  
     setRequestProperty("accept", "*/*");  
   }  
   if (getRequestProperty("Content-type") == null){  
     setRequestProperty("Content-type", "application/x-www-form-urlencoded");  
106    }    }
107    
108    // Write all req_props name-value pairs to the output writer    /**
109    Iterator itr = getRequestProperties().entrySet().iterator();     * Connects to the remote host, sends the request, and parses the reply
110    while(itr.hasNext()){     * code and header information returned
111      Map.Entry e = (Map.Entry) itr.next();     */
112      out_writer.print(e.getKey() + ": " + e.getValue() + "\r\n");    public void connect() throws IOException
113    }    {
114        // Connect up
115        if (url.getPort() == -1)
116          socket = new Socket(url.getHost(), 80);
117        else
118          socket = new Socket(url.getHost(), url.getPort());
119    
120        out_stream = new BufferedOutputStream(socket.getOutputStream());
121        out_writer = new PrintWriter(new OutputStreamWriter(out_stream, "8859_1"));
122    
123    // Write Content-type and length      connected = true;
   if(buffered_out_stream != null){  
     out_writer.print("Content-type: application/x-www-form-urlencoded\r\n");  
     out_writer.print("Content-length: "  
                     + String.valueOf(buffered_out_stream.size()) + "\r\n");  
124    }    }
125    
126    // One more CR-LF indicates end of header    /**
127    out_writer.print("\r\n");     * write HTTP request header and content to out_writer
128    out_writer.flush();     */
129      void SendRequest() throws IOException
130    // Write content    {
131    if(buffered_out_stream != null){      // Send the request
132      buffered_out_stream.writeTo(out_stream);      out_writer.print(getRequestMethod() + " " + getURL().getFile()
133      out_stream.flush();                       + " HTTP/1.1\r\n");
134    
135        if (getRequestProperty ("host") == null)
136          {
137            setRequestProperty ("Host", getURL().getHost());
138          }
139        
140        if (getRequestProperty ("Connection") == null)
141          {
142            setRequestProperty ("Connection", "Close");
143          }
144        
145        if (getRequestProperty ("user-agent") == null)
146          {
147            setRequestProperty ("user-agent", "gnu-classpath/"
148                                + System.getProperty ("classpath.version"));
149          }
150        
151        if (getRequestProperty ("accept") == null)
152          {
153            setRequestProperty ("accept", "*/*");
154          }
155        
156        if (getRequestProperty ("Content-type") == null)
157          {
158            setRequestProperty ("Content-type", "application/x-www-form-urlencoded");
159          }
160    
161        // Write all req_props name-value pairs to the output writer
162        Iterator itr = getRequestProperties().entrySet().iterator();
163    
164        while (itr.hasNext())
165          {
166            Map.Entry e = (Map.Entry) itr.next();
167            out_writer.print (e.getKey() + ": " + e.getValue() + "\r\n");
168          }
169    
170        // Write Content-type and length
171        if (buffered_out_stream != null)
172          {
173            out_writer.print ("Content-type: application/x-www-form-urlencoded\r\n");
174            out_writer.print ("Content-length: "
175                              + String.valueOf (buffered_out_stream.size()) + "\r\n");
176          }
177    
178        // One more CR-LF indicates end of header
179        out_writer.print ("\r\n");
180        out_writer.flush();
181    
182        // Write content
183        if (buffered_out_stream != null)
184          {
185            buffered_out_stream.writeTo (out_stream);
186            out_stream.flush();
187          }
188    }    }
 }  
189    
190  /**    /**
191    * Read HTTP reply from in_stream     * Read HTTP reply from in_stream
192    */     */
193  void ReceiveReply() throws IOException    void ReceiveReply() throws IOException
194  {    {
195    // Parse the reply      // Parse the reply
196    String line = in_stream.readLine();      String line = in_stream.readLine();
197    String saveline = line;      String saveline = line;
198        int idx = line.indexOf (" ");
199    int idx = line.indexOf(" " );      
200    if ((idx == -1) || (line.length() < (idx + 6)))      if ((idx == -1)
201      throw new IOException("Server reply was unparseable: " + saveline);          || (line.length() < (idx + 6)))
   
   line = line.substring(idx + 1);  
   String code = line.substring(0, 3);  
   try  
     {  
       responseCode = Integer.parseInt(code);  
     }  
   catch (NumberFormatException e)  
     {  
202        throw new IOException("Server reply was unparseable: " + saveline);        throw new IOException("Server reply was unparseable: " + saveline);
     }  
   responseMessage = line.substring(4);  
   
   // Now read the header lines  
   String key = null, value = null;  
   for (;;)  
     {  
       line = in_stream.readLine();  
       if (line.equals(""))  
         break;  
   
       // Check for folded lines  
       if (line.startsWith(" ") || line.startsWith("\t"))  
         {  
           // Trim off leading space  
           do  
             {  
               if (line.length() == 1)  
                 throw new IOException("Server header lines were unparseable: "  
                                 + line);  
   
               line = line.substring(1);  
             }  
           while (line.startsWith(" ") || line.startsWith("\t"));  
   
           value = value + " " + line;  
         }  
       else  
         {  
           if (key != null)  
             {  
               headers.addHeaderField(key, value);  
               key = null;  
               value = null;  
             }  
   
           // Parse out key and value  
           idx = line.indexOf(":");  
           if ((idx == -1) || (line.length() < (idx + 2)))  
             throw new IOException("Server header lines were unparseable: "  
                             + line);  
   
           key = line.substring(0, idx);  
           value = line.substring(idx + 1);  
   
           // Trim off leading space  
           while (value.startsWith(" ") || value.startsWith("\t"))  
             {  
               if (value.length() == 1)  
                 throw new IOException("Server header lines were unparseable: "  
                                 + line);  
   
               value = value.substring(1);  
             }  
          }  
      }  
   if (key != null)  
     {  
       headers.addHeaderField(key, value);  
     }  
 }  
 /*************************************************************************/  
   
 /**  
   * Disconnects from the remote server  
   */  
 public void  
 disconnect()  
 {  
   try  
     {  
       if (socket != null)  
         socket.close();  
     }  
   catch(IOException e) { ; }  
 }  
   
 /*************************************************************************/  
   
 /**  
   * Overrides java.net.HttpURLConnection.setRequestMethod() in order to  
   * restrict the available methods to only those we support.  
   *  
   * @param method The RequestMethod to use  
   *  
   * @exception ProtocolException If the specified method is not valid  
   */  
 public void  
 setRequestMethod(String method) throws ProtocolException  
 {  
   method = method.toUpperCase();  
   if (method.equals("GET") || method.equals("HEAD") || method.equals("POST"))  
     super.setRequestMethod(method);  
   else  
     throw new ProtocolException("Unsupported or unknown request method " +  
                                 method);  
 }  
203    
204  /*************************************************************************/      line = line.substring (idx + 1);
205        String code = line.substring (0, 3);
206        
207        try
208          {
209            responseCode = Integer.parseInt (code);
210          }
211        catch (NumberFormatException e)
212          {
213            throw new IOException ("Server reply was unparseable: " + saveline);
214          }
215        
216        responseMessage = line.substring (4);
217    
218  /**      // Now read the header lines
219    * Return a boolean indicating whether or not this connection is      String key = null, value = null;
220    * going through a proxy      
221    *      for (;;)
222    * @return true if using a proxy, false otherwise        {
223    */          line = in_stream.readLine();
224  public boolean          
225  usingProxy()          if (line.equals(""))
226  {            break;
227    return(false);  
228  }          // Check for folded lines
229            if (line.startsWith (" ")
230                || line.startsWith("\t"))
231              {
232                // Trim off leading space
233                do
234                  {
235                    if (line.length() == 1)
236                      throw new IOException("Server header lines were unparseable: "
237                                            + line);
238    
239                    line = line.substring (1);
240                  }
241                while (line.startsWith(" ")
242                       || line.startsWith("\t"));
243    
244                value = value + " " + line;
245              }
246            else
247              {
248                if (key != null)
249                  {
250                    headers.addHeaderField (key, value);
251                    key = null;
252                    value = null;
253                  }
254    
255                // Parse out key and value
256                idx = line.indexOf (":");
257                if ((idx == -1)
258                    || (line.length() < (idx + 2)))
259                  throw new IOException ("Server header lines were unparseable: "
260                                         + line);
261    
262                key = line.substring (0, idx);
263                value = line.substring (idx + 1);
264    
265                // Trim off leading space
266                while (value.startsWith (" ")
267                       || value.startsWith ("\t"))
268                  {
269                    if (value.length() == 1)
270                      throw new IOException ("Server header lines were unparseable: "
271                                             + line);
272    
273                    value = value.substring (1);
274                  }
275              }
276          }
277        
278        if (key != null)
279          {
280            headers.addHeaderField (key, value);
281          }
282      }
283    
284  /*************************************************************************/    /**
285       * Disconnects from the remote server
286       */
287      public void disconnect()
288      {
289        try
290          {
291            if (socket != null)
292              socket.close();
293          }
294        catch (IOException e)
295          {
296          }
297      }
298    
299  /**    /**
300    * This method returns the header field key at the specified numeric     * Overrides java.net.HttpURLConnection.setRequestMethod() in order to
301    * index.     * restrict the available methods to only those we support.
302    *     *
303    * @param n The index into the header field array     * @param method The RequestMethod to use
304    *     *
305    * @return The name of the header field key, or <code>null</code> if the     * @exception ProtocolException If the specified method is not valid
306    * specified index is not valid.     */
307    */    public void setRequestMethod (String method) throws ProtocolException
308  public String    {
309  getHeaderFieldKey(int n)      method = method.toUpperCase();
310  {      
311    return(headers.getHeaderFieldKeyByIndex(n));      if (method.equals("GET")
312  }          || method.equals("HEAD")
313            || method.equals("POST"))
314          super.setRequestMethod (method);
315        else
316          throw new ProtocolException ("Unsupported or unknown request method " +
317                                       method);
318      }
319    
320  /*************************************************************************/    /**
321       * Return a boolean indicating whether or not this connection is
322       * going through a proxy
323       *
324       * @return true if using a proxy, false otherwise
325       */
326      public boolean usingProxy()
327      {
328        return false;
329      }
330    
331  /**    /**
332    * This method returns the header field value at the specified numeric     * This method returns the header field key at the specified numeric
333    * index.     * index.
334    *     *
335    * @param n The index into the header field array     * @param n The index into the header field array
336    *     *
337    * @return The value of the specified header field, or <code>null</code>     * @return The name of the header field key, or <code>null</code> if the
338    * if the specified index is not valid.     * specified index is not valid.
339    */     */
340  public String    public String getHeaderFieldKey (int n)
341  getHeaderField(int n)    {
342  {      return headers.getHeaderFieldKeyByIndex (n);
343    return(headers.getHeaderFieldValueByIndex(n));    }
 }  
344    
345  /*************************************************************************/    /**
346       * This method returns the header field value at the specified numeric
347       * index.
348       *
349       * @param n The index into the header field array
350       *
351       * @return The value of the specified header field, or <code>null</code>
352       * if the specified index is not valid.
353       */
354      public String getHeaderField (int n)
355      {
356        return headers.getHeaderFieldValueByIndex (n);
357      }
358    
359  /**    /**
360    * Returns an InputStream for reading from this connection.  This stream     * Returns an InputStream for reading from this connection.  This stream
361    * will be "queued up" for reading just the contents of the requested file.     * will be "queued up" for reading just the contents of the requested file.
362    * Overrides URLConnection.getInputStream()     * Overrides URLConnection.getInputStream()
363    *     *
364    * @return An InputStream for this connection.     * @return An InputStream for this connection.
365    *     *
366    * @exception IOException If an error occurs     * @exception IOException If an error occurs
367    */     */
368  public InputStream    public InputStream getInputStream() throws IOException
369  getInputStream() throws IOException    {
370  {      if(in_stream != null)
371    if(in_stream != null)        return in_stream;
      return in_stream;  
372    
373    if (!connected)      if (!connected)
374      connect();        connect();
375    
376    in_stream      in_stream
377          = new DataInputStream(new BufferedInputStream(socket.getInputStream()));        = new DataInputStream (new BufferedInputStream (socket.getInputStream()));
378        
379    SendRequest();      SendRequest();
380    ReceiveReply();      ReceiveReply();
381    
382    return(in_stream);      return in_stream;
383  }    }
384    
385  public java.io.OutputStream    public OutputStream getOutputStream() throws IOException
386  getOutputStream() throws java.io.IOException    {
387  {      if (!doOutput)
   if(!doOutput)  
388        throw new ProtocolException        throw new ProtocolException
389                ("Want output stream while haven't setDoOutput(true)");          ("Want output stream while haven't setDoOutput(true)");
390    if(!method.equals("POST")) //But we might support "PUT" in future      
391        setRequestMethod("POST");      if (!method.equals ("POST")) //But we might support "PUT" in future
392          setRequestMethod ("POST");
393        
394    if (!connected)      if (!connected)
395      connect();        connect();
396        
397    if(buffered_out_stream == null)      if(buffered_out_stream == null)
398      buffered_out_stream = new ByteArrayOutputStream(256); //default is too small        buffered_out_stream = new ByteArrayOutputStream (256); //default is too small
399            
400    return buffered_out_stream;      return buffered_out_stream;
401  }    }
402    
403  } // class HttpURLConnection  } // class HttpURLConnection
   

Legend:
Removed from v.1.5  
changed lines
  Added in v.1.6

savannah-hackers-public@gnu.org
ViewVC Help
Powered by ViewVC 1.1.26