`
兩ting
  • 浏览: 75399 次
  • 性别: Icon_minigender_2
  • 来自: 成都
社区版块
存档分类
最新评论

URL中文问题

阅读更多

最近使用HttpClient,和Java的java.net.URL,url有中文都会失败。

听徐师兄说HttpClient有URI这个类可以使用:

Java代码  收藏代码
  1. URI uri = new URI(url,false,"UTF-8");  
  2. String url = uri.toString();  

 例如,发送一个get请求获得一个带有中文链接的图片:

Java代码  收藏代码
  1. import java.io.BufferedInputStream;  
  2. import java.io.BufferedOutputStream;  
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5.   
  6. import org.apache.commons.httpclient.HttpClient;  
  7. import org.apache.commons.httpclient.HttpException;  
  8. import org.apache.commons.httpclient.URI;  
  9. import org.apache.commons.httpclient.methods.GetMethod;  
  10. /** 
  11.  * @author fuliang 
  12.  */  
  13. public class Test {  
  14.     public static void main(String[] args) throws HttpException, IOException {  
  15.         String url = "http://www.byecity.com/photoocean/photo/全球图片/亚洲/柬埔寨/s/7723132569.jpg";  
  16.         GetMethod get = null;  
  17.         BufferedInputStream bis = null;  
  18.         BufferedOutputStream bos = null;  
  19.           
  20.         try {  
  21.             URI uri = new URI(url,false,"UTF-8");  
  22.             HttpClient hc = new HttpClient();  
  23.             get = new GetMethod(uri.toString());  
  24.             int status = hc.executeMethod(get);  
  25.             if (status == 200) {  
  26.                 bis = new BufferedInputStream(get  
  27.                         .getResponseBodyAsStream());  
  28.                 bos = new BufferedOutputStream(  
  29.                         new FileOutputStream("/home/fuliang/photo.jpg"));  
  30.   
  31.                 byte[] buffer = new byte[1024];  
  32.                 int len = 0;  
  33.                 while ((len = bis.read(buffer)) != -1) {  
  34.                     bos.write(buffer, 0, len);  
  35.                 }  
  36.             }  
  37.         } finally {  
  38.             if(get != null){  
  39.                 get.releaseConnection();  
  40.             }  
  41.             if(bis != null){  
  42.                 bis.close();  
  43.             }  
  44.             if(bos != null){  
  45.                 bos.close();  
  46.             }  
  47.         }  
  48.     }  
  49. }  

 如果使用java.net.URL而不想引入httpclient的包,我写了一个方法可以基本解决中文url的问题,对非ascii码进行encoding(健壮性肯定没有httpclient那个好,也可以直接把httpclient中的那个源码摘出来用):

Java代码  收藏代码
  1. import java.io.UnsupportedEncodingException;  
  2. import java.net.URLEncoder;  
  3.   
  4. public class URLUtil {  
  5.     public static String encodeURL(String url,String encode)  
  6.             throws UnsupportedEncodingException {  
  7.         StringBuilder sb = new StringBuilder();  
  8.         StringBuilder noAsciiPart = new StringBuilder();  
  9.         for (int i = 0; i < url.length(); i++) {  
  10.             char c = url.charAt(i);  
  11.             if (c > 255) {  
  12.                 noAsciiPart.append(c);  
  13.             } else {  
  14.                 if (noAsciiPart.length() != 0) {  
  15.                     sb.append(URLEncoder.encode(noAsciiPart.toString(),encode));  
  16.                     noAsciiPart.delete(0, noAsciiPart.length());  
  17.                 }  
  18.                 sb.append(c);  
  19.             }  
  20.         }  
  21.         return sb.toString();  
  22.     }  
  23. }  

举一个同样使用java.net.URL下载的例子:

Java代码  收藏代码
  1. import java.io.BufferedInputStream;  
  2. import java.io.BufferedOutputStream;  
  3. import java.io.FileNotFoundException;  
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7. import java.io.OutputStream;  
  8. import java.net.MalformedURLException;  
  9. import java.net.URL;  
  10. import java.net.URLConnection;  
  11.   
  12. import org.apache.log4j.Logger;  
  13.   
  14. public class Downloader {  
  15.     private static Logger logger = Logger.getLogger(Downloader.class);  
  16.   
  17.     public static boolean download(String urlString, String savePath) {  
  18.         BufferedInputStream bis = null;  
  19.         BufferedOutputStream bos = null;  
  20.         try {  
  21.             urlString = URLUtil.encodeURL(urlString,"UTF-8");  
  22.             bis = new BufferedInputStream(  
  23.                     getDownloadInputStream(urlString));  
  24.   
  25.             bos = new BufferedOutputStream(new FileOutputStream(savePath));  
  26.   
  27.             byte[] buffer = new byte[2048];  
  28.             int len;  
  29.             while ((len = bis.read(buffer,0,buffer.length)) != -1) {  
  30.                 bos.write(buffer, 0, len);  
  31.             }  
  32.         } catch (MalformedURLException e) {  
  33.             logger.error("Error url: " + urlString, e);  
  34.             return false;  
  35.         } catch (IOException e) {  
  36.             logger.error("Get connection " + urlString + "failed",  
  37.                     e);  
  38.             return false;  
  39.         } finally {  
  40.             try {  
  41.                 if (bis != null) {  
  42.                     bis.close();  
  43.                 }  
  44.                 if (bos != null) {  
  45.                     bos.close();  
  46.                 }  
  47.             } catch (IOException e) {  
  48.                 logger.error("close failed", e);  
  49.                 return false;  
  50.             }  
  51.         }  
  52.         return true;  
  53.     }  
  54.       
  55.     private static InputStream getDownloadInputStream(String urlString)  
  56.             throws IOException {  
  57.         URL url = new URL(urlString);  
  58.         URLConnection connection = url.openConnection();  
  59.         InputStream inputStream = connection.getInputStream();  
  60.         return inputStream;  
  61.     }  
  62.   
  63.     public static OutputStream getSavaOutputStream(String path)  
  64.             throws FileNotFoundException {  
  65.         OutputStream fileOutputStream = new FileOutputStream(path);  
  66.         return fileOutputStream;  
  67.     }  
  68.       
  69.     public static void main(String[] args) {  
  70.         download("http://www.byecity.com/photoocean/photo/全球图片/欧洲/希腊/s/76291161.jpg","/home/fuliang/test.jpg");  
  71.     }  
  72. }  

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics