使用HttpURLConnection 下载页面内容

public class HttpURLRequestUtil {
	/**
	 * 获取给定URL对应请求的返回页面信息。
	 */
	public static String getPageCode(String url) {
		StringBuffer temp = null;
		URL currentUrl;
		try {
			currentUrl = new URL(url);
			HttpURLConnection httpcon = (HttpURLConnection) currentUrl
					.openConnection();
			httpcon.connect();
			InputStreamReader in = new InputStreamReader(
					httpcon.getInputStream());
			BufferedReader buf = new BufferedReader(in);
			String line = buf.readLine();
			if (line != null) {
				temp = new StringBuffer();
				while (line != null) {
					temp.append(line);
					line = buf.readLine();
				}
			}
			buf.close();
			in.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return (temp == null ? null : temp.toString());
	}

	/**
	 * 获取给定URL和请求参数对应请求的返回页面信息。
	 * 
	 * @param url
	 *            给定URL
	 * @param paras
	 *            给定请求参数
	 * @return 请求的返回页面信息
	 * @since 1.0
	 */
	public static String getPageCode(String url, Properties paras) {
		if (paras == null)
			return getPageCode(url);
		// 带有参数的请求实现
		String parameters = changePropertyToString(paras);

		StringBuffer temp = null;
		URL l_url = null;
		try {
			l_url = new URL(url);
			HttpURLConnection huc = (HttpURLConnection) l_url.openConnection();
			// 设置允许output
			huc.setDoOutput(true);
			// 设置为post方式
			huc.setRequestMethod("POST");// POST GET
			huc.setRequestProperty("user-agent", "mozilla/4.7 [en] (win98; i)");

			// post信息
			OutputStream os = huc.getOutputStream();
			os.write(parameters.getBytes("gb2312"));// gbk
													// 注意字符集的选择,选择不当会导致获取信息失败或有误。utf-8
			os.close();

			BufferedReader br = new BufferedReader(new InputStreamReader(
					huc.getInputStream()));
			huc.connect();
			String line = br.readLine();
			if (line != null) {
				temp = new StringBuffer();
				while (line != null) {
					temp.append(line);
					line = br.readLine();
				}
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return (temp == null ? null : temp.toString());

	}

	/**
	 * 将Properties参数转换成字符串请求参数。
	 * 
	 * @param paras
	 *            Properties参数
	 * @return 字符串请求参数
	 * @since 1.0
	 */
	private static String changePropertyToString(Properties paras) {
		StringBuffer temp = new StringBuffer();
		String[] reqKeys = (String[]) paras.keySet().toArray(new String[0]);
		for (int i = 0; i < reqKeys.length; i++) {
			if (i > 0) {
				temp.append("&");
				temp.append(reqKeys[i] + "=" + paras.getProperty(reqKeys[i]));
			} else {
				temp.append(reqKeys[i] + "=" + paras.getProperty(reqKeys[i]));
			}
		}
		return temp.toString();
	}
}
几个说明:函数用来发送get和post请求,有一辅助函数实现编码转换,最后返回页面字符串
函数是静态函数
HttpURLConnectionhuc = (HttpURLConnection) l_url.openConnection();此句中的转化

你可能感兴趣的:(properties,String,null,url,Parameters)