11package com .spun .util .io ;
22
33import com .spun .util .ObjectUtils ;
4- import org .apache .commons .httpclient .HttpClient ;
5- import org .apache .commons .httpclient .methods .GetMethod ;
64
5+ import java .io .BufferedReader ;
76import java .io .InputStream ;
7+ import java .io .InputStreamReader ;
8+ import java .net .HttpURLConnection ;
89import java .net .URL ;
910
1011/**
@@ -14,34 +15,77 @@ public class NetUtils
1415{
1516 public static String loadWebPage (String url , String parameters )
1617 {
18+ HttpURLConnection connection = null ;
1719 try
1820 {
19- HttpClient client = new HttpClient ();
20- GetMethod method = new GetMethod (url );
21- if (parameters != null )
21+ if (parameters != null && !parameters .isEmpty ())
2222 {
23- method . setQueryString ( parameters ) ;
23+ url += "?" + parameters ;
2424 }
25- client .executeMethod (method );
26- String html = method .getResponseBodyAsString ();
27- return html ;
25+ URL urlObj = new URL (url );
26+ connection = (HttpURLConnection ) urlObj .openConnection ();
27+ connection .setRequestMethod ("GET" );
28+ connection .connect ();
29+
30+ int responseCode = connection .getResponseCode ();
31+ if (responseCode != HttpURLConnection .HTTP_OK )
32+ {
33+ throw new RuntimeException ("Failed to load web page, response code: " + responseCode );
34+ }
35+
36+ InputStream inputStream = connection .getInputStream ();
37+ BufferedReader reader = new BufferedReader (new InputStreamReader (inputStream ));
38+ StringBuilder html = new StringBuilder ();
39+ String line ;
40+ while ((line = reader .readLine ()) != null )
41+ {
42+ html .append (line );
43+ }
44+ reader .close ();
45+ return html .toString ();
2846 }
2947 catch (Exception e )
3048 {
3149 throw ObjectUtils .throwAsError (e );
3250 }
51+ finally
52+ {
53+ if (connection != null )
54+ {
55+ connection .disconnect ();
56+ }
57+ }
3358 }
59+
3460 public static String readWebpage (String query )
3561 {
62+ HttpURLConnection connection = null ;
3663 try
3764 {
3865 URL url = new URL (query );
39- InputStream inputStream = url .openStream ();
66+ connection = (HttpURLConnection ) url .openConnection ();
67+ connection .setRequestMethod ("GET" );
68+ connection .connect ();
69+
70+ int responseCode = connection .getResponseCode ();
71+ if (responseCode != HttpURLConnection .HTTP_OK )
72+ {
73+ throw new RuntimeException ("Failed to read web page, response code: " + responseCode );
74+ }
75+
76+ InputStream inputStream = connection .getInputStream ();
4077 return FileUtils .readStream (inputStream );
4178 }
4279 catch (Exception e )
4380 {
4481 throw ObjectUtils .throwAsError (e );
4582 }
83+ finally
84+ {
85+ if (connection != null )
86+ {
87+ connection .disconnect ();
88+ }
89+ }
4690 }
4791}
0 commit comments