Docjar: A Java Source and Docuemnt Enginecom.*    java.*    javax.*    org.*    all    new    plug-in

Quick Search    Search Deep

Source code: com/telefonicasoluciones/search/server/util/HTTPClient.java


1   package com.telefonicasoluciones.search.server.util;
2   
3   /**
4    * Insert the type's description here.
5    * Creation date: (13/02/2002 8:53:21)
6    * @author: Ricardo Lorenzo
7    */
8   import java.net.*;
9   import java.util.*;
10  import java.io.*;
11   
12  public class HTTPClient {
13    private static final int HTTP_PORT = 80;
14    private static final char CR = '\n';
15    private String server;
16    private String document;
17    private Socket connector;
18    private BufferedInputStream istream;
19    private OutputStream ostream;
20    private ArrayList cookie;
21    private String contentType;
22          private int contentLength;
23    private String header;
24    private String content;
25    private boolean connected;
26          int read_length;
27  /**
28   * HLUrl constructor comment.
29   */
30      public HTTPClient(String server) {
31    this.server = server;
32    connected = false;
33    cookie = new ArrayList();
34      }
35  /**
36   * Insert the method's description here.
37   * Creation date: (21/01/2002 8:08:05)
38   */
39      private void connect() throws HTTPClientException {
40    try {
41              InetAddress server = InetAddress.getByName(this.server);
42              connector = new Socket(this.server,HTTP_PORT);
43              ostream = connector.getOutputStream();
44              istream = new BufferedInputStream(connector.getInputStream());
45              connected = true;
46    } catch (UnknownHostException uhe) {
47      throw new HTTPClientException("Connect unknown host ["+uhe.getMessage()+"]");
48    } catch (IOException ioe) {
49      throw new HTTPClientException("Connect i/o error  ["+ioe.getMessage()+"]");
50    }
51      }
52  /**
53   * Insert the method's description here.
54   * Creation date: (21/01/2002 8:36:39)
55   */
56      private void disconnect() throws HTTPClientException {
57    if(connected) {
58              try {
59                  connector.close();
60                  istream = null;
61                  ostream = null;
62                  connected = false;
63              } catch (IOException ioe) {
64                  throw new HTTPClientException("Disconnect i/o error ["+ioe.getMessage()+"]");
65              } catch (NullPointerException npe) {
66                  throw new HTTPClientException("Disconnect [NullPointer]");
67              }
68    }
69      }
70  /**
71   * Permite ejecutar el método HTTP GET.
72   * Creation date: (21/01/2002 8:40:13)
73   * @param path java.lang.String
74   */
75      private void get(String path) throws HTTPClientException {
76    try {
77              if(!connected)
78                  connect();
79              if(path.equals("")||path.equals(" ")) path="/";
80              String command = "GET ";
81              command += path + " HTTP/1.1" + CR;
82              command += "Accept:*/*" + CR;
83              command += "Accept-Encoding:gzip,deflate" + CR;
84              command += "User-Agent:Headlight v1.3" + CR;
85              command += "Host:" + server + CR;
86              command += "Connection:close" + CR;
87              command += "Cache-Control:no-cache" + CR;
88              for(int i=0;i<cookie.size();i++) {
89                  command += "Cookie: " + cookie.get(i) + CR;
90              }
91              command += CR;
92              ostream.write(command.getBytes());
93              ostream.flush();
94              readResponse();
95              if(connected)
96                  disconnect();
97    } catch (HTTPClientException httpce) {
98              throw httpce;
99          } catch (IOException ioe) {
100             throw new HTTPClientException("GET i/o error ["+ioe.getMessage()+"]");
101   } catch (NullPointerException npe) {
102             throw new HTTPClientException("GET error [Nullpointer]");
103   } catch (Exception e) {
104             throw new HTTPClientException("GET "+e.getClass()+" ["+e.getMessage()+"]");
105   }
106 }
107 /**
108  * Insert the method's description here.
109  * Creation date: (22/01/2002 8:07:09)
110  * @return java.lang.String
111  */
112     public java.lang.String getContent() {
113   return content;
114     }
115 /**
116  * Insert the method's description here.
117  * Creation date: (13/02/2002 9:19:31)
118  * @return java.lang.String
119  */
120     public String getContentType() {
121   return contentType;
122     }
123 /**
124  * Insert the method's description here.
125  * Creation date: (13/02/2002 9:19:31)
126  * @return java.lang.String
127  */
128     public final static String getDocumentString(String urlString) {
129   String server = null;
130   if(urlString.indexOf("http://")!=-1) {
131             server = urlString.substring("http://".length()+1);
132   } else {
133             server = urlString;
134   }
135   String document = null;
136   if(server.indexOf("/")!=-1) {
137             document = server.substring(server.indexOf("/"));
138   } else {
139             document = "/";
140   }
141   return document;
142     }
143 /**
144  * Insert the method's description here.
145  * Creation date: (13/02/2002 12:50:16)
146  * @return java.lang.String
147  */
148     public String getFile() {
149   return document;
150     }
151 /**
152  * Insert the method's description here.
153  * Creation date: (22/01/2002 8:07:23)
154  * @return java.lang.String
155  */
156     public java.lang.String getHeader() {
157   return header;
158     }
159 /**
160  * Insert the method's description here.
161  * Creation date: (13/02/2002 12:52:41)
162  * @return java.lang.String
163  */
164     public String getHost() {
165   return server;
166     }
167 /**
168  * Insert the method's description here.
169  * Creation date: (13/02/2002 10:50:56)
170  * @return java.lang.String
171  * @param urlString java.lang.String
172  */
173     public final static String getServerString(String urlString) {
174   String server = null;
175   if(urlString.indexOf("http://")!=-1) {
176             server = urlString.substring("http://".length());
177   } else {
178             server = urlString;
179   }
180   if(server.indexOf("/")!=-1) {
181             server = server.substring(0,server.indexOf("/"));
182   }
183   return server;
184     }
185 /**
186  * Insert the method's description here.
187  * Creation date: (13/02/2002 12:27:46)
188  * @return java.lang.String
189  */
190     public String getUrlString() {
191   return new String("http://"+server+document);
192     }
193 /**
194  * Insert the method's description here.
195  * Creation date: (13/02/2002 9:20:46)
196  * @param document java.lang.String
197  */
198     public void load(String document) throws HTTPClientException {
199   this.document = document;
200   if(document.indexOf("?") != -1) {
201             String httpFile = document.substring(0,document.indexOf("?"));
202             String httpQuery = document.substring(document.indexOf("?")+1, document.length());
203             System.out.println("Link:"+document);
204             this.post(httpFile, httpQuery);
205   } else {
206             this.get(document);
207   }  
208     }
209 /**
210  * Insert the method's description here.
211  * Creation date: (21/01/2002 8:43:53)
212  */
213     private void post(String path, String query) throws HTTPClientException {
214   try {
215             if(!connected)
216                 connect();
217             if(path.equals("")||path.equals(" ")) path="/";
218             String command = "POST ";
219             command += path + " HTTP/1.1" + CR;
220             command += "Host: " + server + CR;
221             command += "Accept: */*" + CR;
222             command += "Accept-Encoding: gzip, deflate" + CR;
223             command += "User-Agent: Headlight v1.3" + CR;
224             command += "Connection: close" + CR;
225             command += "Cache-Control: no-cache" + CR;
226             for(int i=0;i<cookie.size();i++) {
227                 command += "Cookie: " + cookie.get(i) + CR;
228             }
229             command += "Content-type: application/x-www-form-urlencoded" + CR;
230             command += "Content-Length: " + query.length() + CR;
231             command += CR;
232             command += query + CR;
233             ostream.write(command.getBytes());
234             ostream.flush();
235             readResponse();
236             if(connected)
237                 disconnect();
238   } catch (HTTPClientException httpce) {
239             throw httpce;
240         } catch (IOException ioe) {
241             throw new HTTPClientException("POST i/o error ["+ioe.getMessage()+"]");
242   } catch (NullPointerException npe) {
243             throw new HTTPClientException("POST error [nullpointer]");
244   } catch (Exception e) {
245             throw new HTTPClientException("POST "+e.getClass()+" ["+e.getMessage()+"]");
246   }
247     }
248     private void readResponse() throws Exception {
249   try {
250             StringBuffer buffer = new StringBuffer();
251             String line = null;
252             boolean wait = false;
253             while(true) {
254                 line = readHTTPLine();
255                 if(line!=null&&line.indexOf(" ")!=-1) { 
256                     try {
257                         StringTokenizer st = new StringTokenizer(line," ");
258                         int n;
259                         st.nextToken();
260                         if(st.hasMoreTokens()) {
261                             n = Integer.parseInt(st.nextToken());
262                             if(n==100) {
263                                 wait = true;
264                                 continue; 
265                             } else if(n==200) {
266                                 wait = false;
267                                 while((line=readHTTPLine())!=null&&!line.equals("\r\n")&&!line.equals("\n")) {
268                                     if(line.toLowerCase().indexOf("set-cookie")!=-1) {
269                                         if(line.indexOf(";")!=-1)
270                                             cookie.add(line.substring(line.indexOf(":")+1,line.indexOf(";")).trim());
271                                         else
272                                             cookie.add(line.substring(line.indexOf(":")+1,line.length()).trim());
273                                     }
274                                     if(line.toLowerCase().indexOf("content-type")!=-1) {
275                                         contentType = line.substring(line.indexOf(":")+1,line.length()).trim();
276                                     }
277                                     if(line.toLowerCase().indexOf("content-length")!=-1) {
278                                         try {
279                                             contentLength = Integer.parseInt(line.substring(line.indexOf(":")+1,line.length()).trim());
280                                         } catch(NumberFormatException e) {}
281                                     }
282                                     if(line!=null) buffer.append(line);
283                                 }
284                                 header = buffer.toString();
285                                 break;
286                             } else {
287                                 throw new HTTPClientException(line.substring(line.indexOf(" ")+1,line.length()));
288                             }
289                         }                       
290                     } catch(NumberFormatException nfe) {
291                         if(wait) { continue; } else { break; }
292                     } catch(Exception e) { 
293                         throw new HTTPClientException(e.getMessage());
294                     }
295                 } else {
296                     throw new HTTPClientException("HTTP response error from "+document);  
297                 }
298             }
299             buffer.delete(0,buffer.length());
300             read_length=0;
301             while((line=readHTTPLine())!=null) {
302                 buffer.append(line);
303             }
304             if(buffer.length()>0) { content = buffer.toString(); }
305   } catch (NullPointerException npe) {
306             throw new Exception("ReadResponse nullpointer");
307   } catch (Exception e) {
308             throw new Exception("ReadResponse "+e.getMessage());
309   }
310     }
311     private String readHTTPLine() throws IOException {
312         try {
313             StringBuffer buffer = new StringBuffer();
314             int thisChar;
315             while(istream!=null&&(thisChar=istream.read())!=-1) {
316               switch(thisChar) {
317                     case 10:
318                         buffer.append((char)thisChar);
319                         return buffer.toString();
320                     case 13:
321                         if(istream.available()<=0) { 
322                             buffer.append((char)thisChar);
323                             return buffer.toString();
324                         } else {
325                             if((thisChar=istream.read())==10) {
326                                 buffer.append((char)thisChar);
327                                 return buffer.toString();
328                             } else {
329                                 buffer.append((char)thisChar);
330                             }
331                         }
332                         break;
333                     default:
334                         buffer.append((char)thisChar);
335                         break;
336                 }
337             }
338             if(buffer.length()>0) {
339                 return buffer.toString();
340             } else {
341                 return null;
342             }
343         } catch(IOException ioe) {
344             throw ioe;
345         }
346     }
347 }