1 package zmx.util; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.io.InputStreamReader; 7 import java.io.OutputStreamWriter; 8 import java.io.UnsupportedEncodingException; 9 import java.net.HttpURLConnection; 10 import java.net.InetSocketAddress; 11 import java.net.Proxy; 12 import java.net.URL; 13 import java.net.URLConnection; 14 import java.util.List; 15 import java.util.Map; 16 17 /** 18 * Http请求工具类 19 * 20 */ 21 public class HttpRequestUtil { 22 static boolean proxySet = false; 23 static String proxyHost = "127.0.0.1"; 24 static int proxyPort = 8087; 25 /** 26 * 编码 27 * @param source 28 * @return 29 */ 30 public static String urlEncode(String source,String encode) { 31 String result = source; 32 try { 33 result = java.net.URLEncoder.encode(source,encode); 34 } catch (UnsupportedEncodingException e) { 35 e.printStackTrace(); 36 return "0"; 37 } 38 return result; 39 } 40 41 42 public static String urlEncodeGBK(String source) { 43 String result = source; 44 try { 45 result = java.net.URLEncoder.encode(source,"GBK"); 46 } catch (UnsupportedEncodingException e) { 47 e.printStackTrace(); 48 return "0"; 49 } 50 return result; 51 } 52 /** 53 * 发起http请求获取返回结果 54 * @param req_url 请求地址 55 * @return 56 */ 57 public static String httpRequest(String req_url) { 58 StringBuffer buffer = new StringBuffer(); 59 try { 60 URL url = new URL(req_url); 61 HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection(); 62 63 httpUrlConn.setDoOutput(true); 64 httpUrlConn.setDoInput(true); 65 httpUrlConn.setUseCaches(false); 66 httpUrlConn.setConnectTimeout(50000); 67 httpUrlConn.setReadTimeout(50000); 68 httpUrlConn.setRequestMethod("GET"); 69 // httpUrlConn.setRequestProperty("Accept", "image/png,image/*;q=0.8,*/*;q=0.5"); 70 // httpUrlConn.setRequestProperty("Accept-Encoding", "gzip"); 71 //httpUrlConn.setRequestProperty("Referer", "http://www.hao123.com/"); 72 httpUrlConn.connect(); //发送请求 73 if (httpUrlConn.getResponseCode() == 200) { 74 75 // 将返回的输入流转换成字符串 76 InputStream inputStream = httpUrlConn.getInputStream(); 77 InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8"); 78 BufferedReader bufferedReader = new BufferedReader(inputStreamReader); 79 80 String str = null; 81 while ((str = bufferedReader.readLine()) != null) { 82 buffer.append(str); 83 } 84 bufferedReader.close(); 85 inputStreamReader.close(); 86 // 释放资源 87 inputStream.close(); 88 inputStream = null; 89 httpUrlConn.disconnect(); 90 91 } 92 93 } catch (Exception e) { 94 System.out.println(e.getStackTrace()); 95 } 96 return buffer.toString(); 97 } 98 99 /** 100 * 发送http请求取得返回的输入流 101 * @param requestUrl 请求地址 102 * @return InputStream 103 */ 104 public static InputStream httpRequestIO(String requestUrl) { 105 InputStream inputStream = null; 106 try { 107 URL url = new URL(requestUrl); 108 HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection(); 109 httpUrlConn.setDoInput(true); 110 httpUrlConn.setRequestMethod("GET"); 111 httpUrlConn.connect(); 112 // 获得返回的输入流 113 inputStream = httpUrlConn.getInputStream(); 114 } catch (Exception e) { 115 e.printStackTrace(); 116 } 117 return inputStream; 118 } 119 120 121 /** 122 * 向指定URL发送GET方法的请求 123 * 124 * @param url 125 * 发送请求的URL 126 * @param param 127 * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 128 * @return URL 所代表远程资源的响应结果 129 */ 130 public static String sendGet(String url, String param) { 131 String result = ""; 132 BufferedReader in = null; 133 try { 134 String urlNameString = url + "?" + param; 135 URL realUrl = new URL(urlNameString); 136 // 打开和URL之间的连接 137 URLConnection connection = realUrl.openConnection(); 138 // 设置通用的请求属性 139 connection.setRequestProperty("accept", "*/*"); 140 connection.setRequestProperty("connection", "Keep-Alive"); 141 connection.setRequestProperty("user-agent", 142 "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); 143 // 建立实际的连接 144 connection.connect(); 145 // 获取所有响应头字段 146 Map<String, List<String>> map = connection.getHeaderFields(); 147 // 遍历所有的响应头字段 148 for (String key : map.keySet()) { 149 System.out.println(key + "--->" + map.get(key)); 150 } 151 // 定义 BufferedReader输入流来读取URL的响应 152 in = new BufferedReader(new InputStreamReader( 153 connection.getInputStream())); 154 String line; 155 while ((line = in.readLine()) != null) { 156 result += line; 157 } 158 } catch (Exception e) { 159 System.out.println("发送GET请求出现异常!" + e); 160 e.printStackTrace(); 161 } 162 // 使用finally块来关闭输入流 163 finally { 164 try { 165 if (in != null) { 166 in.close(); 167 } 168 } catch (Exception e2) { 169 e2.printStackTrace(); 170 } 171 } 172 return result; 173 } 174 175 /** 176 * 向指定 URL 发送POST方法的请求 177 * 178 * @param url 179 * 发送请求的 URL 180 * @param param 181 * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 182 * @param isproxy 183 * 是否使用代理模式 184 * @return 所代表远程资源的响应结果 185 */ 186 public static String sendPost(String url, String param,boolean isproxy) { 187 OutputStreamWriter out = null; 188 BufferedReader in = null; 189 String result = ""; 190 try { 191 URL realUrl = new URL(url); 192 HttpURLConnection conn = null; 193 if(isproxy){//使用代理模式 194 @SuppressWarnings("static-access") 195 Proxy proxy = new Proxy(Proxy.Type.DIRECT.HTTP, new InetSocketAddress(proxyHost, proxyPort)); 196 conn = (HttpURLConnection) realUrl.openConnection(proxy); 197 }else{ 198 conn = (HttpURLConnection) realUrl.openConnection(); 199 } 200 // 打开和URL之间的连接 201 202 // 发送POST请求必须设置如下两行 203 conn.setDoOutput(true); 204 conn.setDoInput(true); 205 conn.setRequestMethod("POST"); // POST方法 206 207 208 // 设置通用的请求属性 209 conn.setRequestProperty("accept", "*/*"); 210 conn.setRequestProperty("connection", "Keep-Alive"); 211 conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); 212 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 213 214 conn.connect(); 215 216 // 获取URLConnection对象对应的输出流 217 out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); 218 // 发送请求参数 219 out.write(param); 220 // flush输出流的缓冲 221 out.flush(); 222 // 定义BufferedReader输入流来读取URL的响应 223 in = new BufferedReader( 224 new InputStreamReader(conn.getInputStream())); 225 String line; 226 while ((line = in.readLine()) != null) { 227 result += line; 228 } 229 } catch (Exception e) { 230 System.out.println("发送 POST 请求出现异常!"+e); 231 e.printStackTrace(); 232 } 233 //使用finally块来关闭输出流、输入流 234 finally{ 235 try{ 236 if(out!=null){ 237 out.close(); 238 } 239 if(in!=null){ 240 in.close(); 241 } 242 } 243 catch(IOException ex){ 244 ex.printStackTrace(); 245 } 246 } 247 return result; 248 } 249 250 public static void main(String[] args) { 251 252 String url = "http://www.baidu.com/s"; 253 String para ="word=刘德华"; 254 String sr=HttpRequestUtil.httpRequest(url); 255 //String sr=HttpRequestUtil.sendGet(url,para); 256 System.out.println(sr); 257 258 //demo:代理访问 259 //String sr=HttpRequestUtil.sendPost(url,para,true); 260 //System.out.println(sr); 261 } 262 263 }
学问:纸上得来终觉浅,绝知此事要躬行
为事:工欲善其事,必先利其器。
转载请标注出处!