- /*
- * Created on 2005-9-21
- * Made In GamVan
- */
- package com.gamvan.net;
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.io.UnsupportedEncodingException;
- import java.util.Iterator;
- import java.util.Map;
- import javax.servlet.http.HttpServletRequest;
- /**
- *
- * @author GamVan by 我容易么我
- * Powered by GamVan.com
- */
- public class URL{
- /**
- * 对URL中文进行转码 一般get方式查询参数用到
- * @param str 中文字符串
- * @param coder 编码方式,如 UTF-8GBK
- * @return
- */
- public static String urlEncoder(String str, String coder){
- if(str==null){
- return "";
- }
- if(coder==null || coder.equals("")){
- coder = "UTF-8";
- }
- try {
- str = java.net.URLEncoder.encode(str, coder);
- } catch (UnsupportedEncodingException e) {
- str = "";
- e.printStackTrace();
- }
- return str;
- }
- /**
- * 对URL中文进行反转码,一般get方式查询参数用到
- * @param str 中文字符串
- * @param coder 编码方式,如 UTF-8GBK
- * @return
- */
- public static String urlDecoder(String str, String coder){
- if(str==null){
- return "";
- }
- if(coder==null || coder.equals("")){
- coder = "UTF-8";
- }
- try {
- str = java.net.URLDecoder.decode(str, coder);
- } catch (UnsupportedEncodingException e) {
- str = "";
- e.printStackTrace();
- }
- return str;
- }
- /**
- * 取得请求带参数的URL的方法
- * @param request
- * @return
- */
- public static String getUrl(HttpServletRequest request) {
- StringBuffer originalURL = request.getRequestURL();
- Map parameters = request.getParameterMap();
- if (parameters != null && parameters.size() > 0) {
- originalURL.append("?");
- for (Iterator iter = parameters.keySet().iterator(); iter.hasNext();) {
- String key = (String) iter.next();
- String[] values = (String[]) parameters.get(key);
- for (int i = 0; i < values.length; i++) {
- originalURL.append(key).append("=").append(values[i]).append("&");
- }
- }
- }
- return originalURL.toString();
- }
- /**
- * 取得基于主机名的url,定向根目录的域名。(端口自动识别)
- * @param request
- * @return
- */
- public static String getServerUrl(HttpServletRequest request) {
- String str = "http://" + request.getServerName();
- int port = request.getServerPort();
- if(port!=80){
- str = str + ":" + String.valueOf(port);
- }
- return str;
- }
- /**
- * 根据提供的域名地址返回网页html内容
- * @param domain
- * @return
- */
- public static String getWebContent(String domain){
- StringBuffer sb = new StringBuffer();
- try{
- java.net.URL url = new java.net.URL(domain);
- BufferedReader in =
- new BufferedReader(new InputStreamReader(url.openStream()));
- String line;
- while((line = in.readLine()) != null){
- sb.append(line);
- }
- in.close();
- //System.out.println(url.getContent());
- }catch(Exception e) { // Report any errors that arise
- sb.append(e.toString());
- System.err.println(e);
- System.err.println("Usage: java HttpClient <URL> [<filename>]");
- }
- return sb.toString();
- }
- }