论坛首页 Java企业应用论坛

URL工具类

浏览 7847 次
锁定老帖子 主题:URL工具类
精华帖 (0) :: 良好帖 (0) :: 新手帖 (2) :: 隐藏帖 (0)
作者 正文
   发表时间:2011-05-11   最后修改:2011-05-19
package ssh.util;

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

/**
 * URL工具
 * @author gary
 *
 */
public class URLUtil {

	/**
	 * 对url进行编码
	 */
	public static String encodeURL(String url) {
		try {
			return URLEncoder.encode(url, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 对url进行解码
	 * @param url
	 * @return
	 */
	public static String decodeURL(String url){
		try {
			return URLDecoder.decode(url, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 判断URL地址是否存在
	 * @param url
	 * @return
	 */
	public static boolean isURLExist(String url) {
		try {
			URL u = new URL(url);
			HttpURLConnection urlconn = (HttpURLConnection) u.openConnection();
			int state = urlconn.getResponseCode();
			if (state == 200) {
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			return false;
		}
	}
	
	/**
	 * 将请求参数还原为key=value的形式,for struts2
	 * @param params
	 * @return
	 */
	public static String getParamString(Map<?, ?> params) {
		StringBuffer queryString = new StringBuffer(256);
		Iterator<?> it = params.keySet().iterator();
		int count = 0;
		while (it.hasNext()) {
			String key = (String) it.next();
			String[] param = (String[]) params.get(key);
			for (int i = 0; i < param.length; i++) {
				if (count == 0) {
					count++;
				} else {
					queryString.append("&");
				}
				queryString.append(key);
				queryString.append("=");
				try {
					queryString.append(URLEncoder.encode((String) param[i], "UTF-8"));
				} catch (UnsupportedEncodingException e) {
				}
			}
		}
		return queryString.toString();
	}

	/**
	 * 获得请求的路径及参数
	 * @param request
	 * @return
	 */
	public static String getRequestURL(HttpServletRequest request) {
		StringBuffer originalURL = new StringBuffer(request.getServletPath());
		Map<?,?> parameters = request.getParameterMap();
		if (parameters != null && parameters.size() > 0) {
			originalURL.append("?");
			originalURL.append(getParamString(parameters));
		}
		return originalURL.toString();
	}

	/**
	 * 抓取网页内容,自动识别编码
	 * @param urlString
	 * @return
	 */
	public static String url2Str(String urlString) {
		try {
			StringBuffer html = new StringBuffer();
			URL url = new URL(urlString);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			URLConnection c = url.openConnection();
			c.connect();
			String contentType = c.getContentType();
			String characterEncoding = null;
			int index = contentType.indexOf("charset=");
			if(index == -1){
				characterEncoding = "UTF-8";
			}else{
				characterEncoding = contentType.substring(index + 8, contentType.length());
			}
	        InputStreamReader isr = new InputStreamReader(conn.getInputStream(), characterEncoding);
	        BufferedReader br = new BufferedReader(isr);
	        String temp;
	        while ((temp = br.readLine()) != null) {
	            html.append(temp).append("\n");
	        }
	        br.close();
	        isr.close();
	        return html.toString();
	     } catch (Exception e) {
	        e.printStackTrace();
	        return null;
	     }
	 }
	
	/**
	 * 保存图片到本地 
	 * @param picUrl
	 * 		图片URL地址
	 * @param newFileName
	 * 		保存文件名
	 * @param dir
	 * 		保存目录
	 * @return
	 */
	public static void savePic(String picUrl, String newFileName, String dir){
		try{
			URL url = new URL(picUrl);
			InputStream in = url.openStream();   
			BufferedImage srcImage =  ImageIO.read(url.openStream());
	 
			File img = new File(dir + newFileName);
			
			ImageIO.write(srcImage, "jpg", img);
	        in.close();
    	} catch (IOException e) {   
    		e.printStackTrace();   
    	}
	}
    public static void main(String[] args) {
    	String content = URLUtil.url2Str("http://www.baidu.com");;
    	System.out.println(content);
    }
}
 
   发表时间:2011-05-12  
差点就把你当成个帮组文档了 ^ ^
0 请登录后投票
   发表时间:2011-05-13  
还有点用,收了!
0 请登录后投票
   发表时间:2011-05-13  
竟然 上首页了
0 请登录后投票
   发表时间:2011-05-13  
收了,以后可能用的着
0 请登录后投票
   发表时间:2011-05-13  
int state = urlconn.getResponseCode();  
       if (state == 200) {  

使用返回发为200来判断是否存在不正确吧。

我记得2**都是可能的
0 请登录后投票
   发表时间:2011-05-13  
xbgd 写道
int state = urlconn.getResponseCode();  
       if (state == 200) {  

使用返回发为200来判断是否存在不正确吧。

我记得2**都是可能的



/**
     * Gets the status code from an HTTP response message.
     * For example, in the case of the following status lines:
     * <PRE>
     * HTTP/1.0 200 OK
     * HTTP/1.0 401 Unauthorized
     * </PRE>
     * It will return 200 and 401 respectively.
     * Returns -1 if no code can be discerned
     * from the response (i.e., the response is not valid HTTP).
     * @throws IOException if an error occurred connecting to the server.
     * @return the HTTP Status-Code, or -1
     */
    public int getResponseCode() throws IOException

200 成功
201 已创建
202 已接受
203 非权威性信息
204 无内容
205 重置内容
206 部分内容
0 请登录后投票
   发表时间:2011-05-13   最后修改:2011-05-13
why213344 写道
xbgd 写道
int state = urlconn.getResponseCode();  
       if (state == 200) {  

使用返回发为200来判断是否存在不正确吧。

我记得2**都是可能的



/**
     * Gets the status code from an HTTP response message.
     * For example, in the case of the following status lines:
     * <PRE>
     * HTTP/1.0 200 OK
     * HTTP/1.0 401 Unauthorized
     * </PRE>
     * It will return 200 and 401 respectively.
     * Returns -1 if no code can be discerned
     * from the response (i.e., the response is not valid HTTP).
     * @throws IOException if an error occurred connecting to the server.
     * @return the HTTP Status-Code, or -1
     */
    public int getResponseCode() throws IOException

200 成功
201 已创建
202 已接受
203 非权威性信息
204 无内容
205 重置内容
206 部分内容



唉,500错误(内部错误)都应该是存在的,我看到也觉得有问题呢。

sorry,sorry,感谢楼主先,我已经收藏起来了,O(∩_∩)O哈哈~
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics