最近使用HttpClient,和Java的java.net.URL,url有中文都会失败。
听徐师兄说HttpClient有URI这个类可以使用:
- URI uri = new URI(url,false,"UTF-8");
- String url = uri.toString();
例如,发送一个get请求获得一个带有中文链接的图片:
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import org.apache.commons.httpclient.HttpClient;
- import org.apache.commons.httpclient.HttpException;
- import org.apache.commons.httpclient.URI;
- import org.apache.commons.httpclient.methods.GetMethod;
- /**
- * @author fuliang
- */
- public class Test {
- public static void main(String[] args) throws HttpException, IOException {
- String url = "http://www.byecity.com/photoocean/photo/全球图片/亚洲/柬埔寨/s/7723132569.jpg";
- GetMethod get = null;
- BufferedInputStream bis = null;
- BufferedOutputStream bos = null;
- try {
- URI uri = new URI(url,false,"UTF-8");
- HttpClient hc = new HttpClient();
- get = new GetMethod(uri.toString());
- int status = hc.executeMethod(get);
- if (status == 200) {
- bis = new BufferedInputStream(get
- .getResponseBodyAsStream());
- bos = new BufferedOutputStream(
- new FileOutputStream("/home/fuliang/photo.jpg"));
- byte[] buffer = new byte[1024];
- int len = 0;
- while ((len = bis.read(buffer)) != -1) {
- bos.write(buffer, 0, len);
- }
- }
- } finally {
- if(get != null){
- get.releaseConnection();
- }
- if(bis != null){
- bis.close();
- }
- if(bos != null){
- bos.close();
- }
- }
- }
- }
如果使用java.net.URL而不想引入httpclient的包,我写了一个方法可以基本解决中文url的问题,对非ascii码进行encoding(健壮性肯定没有httpclient那个好,也可以直接把httpclient中的那个源码摘出来用):
- import java.io.UnsupportedEncodingException;
- import java.net.URLEncoder;
- public class URLUtil {
- public static String encodeURL(String url,String encode)
- throws UnsupportedEncodingException {
- StringBuilder sb = new StringBuilder();
- StringBuilder noAsciiPart = new StringBuilder();
- for (int i = 0; i < url.length(); i++) {
- char c = url.charAt(i);
- if (c > 255) {
- noAsciiPart.append(c);
- } else {
- if (noAsciiPart.length() != 0) {
- sb.append(URLEncoder.encode(noAsciiPart.toString(),encode));
- noAsciiPart.delete(0, noAsciiPart.length());
- }
- sb.append(c);
- }
- }
- return sb.toString();
- }
- }
举一个同样使用java.net.URL下载的例子:
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.net.MalformedURLException;
- import java.net.URL;
- import java.net.URLConnection;
- import org.apache.log4j.Logger;
- public class Downloader {
- private static Logger logger = Logger.getLogger(Downloader.class);
- public static boolean download(String urlString, String savePath) {
- BufferedInputStream bis = null;
- BufferedOutputStream bos = null;
- try {
- urlString = URLUtil.encodeURL(urlString,"UTF-8");
- bis = new BufferedInputStream(
- getDownloadInputStream(urlString));
- bos = new BufferedOutputStream(new FileOutputStream(savePath));
- byte[] buffer = new byte[2048];
- int len;
- while ((len = bis.read(buffer,0,buffer.length)) != -1) {
- bos.write(buffer, 0, len);
- }
- } catch (MalformedURLException e) {
- logger.error("Error url: " + urlString, e);
- return false;
- } catch (IOException e) {
- logger.error("Get connection " + urlString + "failed",
- e);
- return false;
- } finally {
- try {
- if (bis != null) {
- bis.close();
- }
- if (bos != null) {
- bos.close();
- }
- } catch (IOException e) {
- logger.error("close failed", e);
- return false;
- }
- }
- return true;
- }
- private static InputStream getDownloadInputStream(String urlString)
- throws IOException {
- URL url = new URL(urlString);
- URLConnection connection = url.openConnection();
- InputStream inputStream = connection.getInputStream();
- return inputStream;
- }
- public static OutputStream getSavaOutputStream(String path)
- throws FileNotFoundException {
- OutputStream fileOutputStream = new FileOutputStream(path);
- return fileOutputStream;
- }
- public static void main(String[] args) {
- download("http://www.byecity.com/photoocean/photo/全球图片/欧洲/希腊/s/76291161.jpg","/home/fuliang/test.jpg");
- }
- }
相关推荐
URL汉字编码问题(及乱码解决)
主要为大家分享了介绍了java中文乱码之解决URL中文乱码问题的方法,感兴趣的小伙伴们可以参考一下
url分类解决URL里面的空格、中文、及其他特殊字符问题
JAVA解决URL路径中含有中文的问题。无论是路径中还是文件名包含中文都可以处理。经测试验证通过。
JS实现URL编码转换中文
在开发过程中遇到了Url的中文乱码问题,经过多次测试,解决了问题,并分享给大家,希望能够你帮助!
通过URLEncoder.encode加密地址栏url上得中文字符, 并可通过java.net.URLDecoder.decode(str, charset)解密中文
搜集了网上的VBA函数,在excel中通过函数将汉字转为两种类型的URL编码,例如将 天空 二字转化为GB2312的“%CC%EC%BF%D5”或者是UTF-8的 “%E5%A4%A9%E7%A9%BA”。方便用于连接转换。VBA相关函数均来自网上,做了小小...
jsp使用URL编码传递中文参数问题.doc 介绍了如何在JSP编写动态网页程序中将字符进行转换
这种问题,初学者应该都会遇到,分享给大家做个参考! from urllib.parse import quote ... 您可能感兴趣的文章:Python 爬虫之超链接 url中含有中文出错及解决办法解决python爬虫中有中文的url问题Py
从A页面通过url传参到B页面时,获取URL中参数出现中文乱码问题,解析url参数的正确方法如下,感兴趣的朋友可以参考下
js 中乱码处理法方式 encodeURIComponent(encodeURIComponent(customerAddress)) ...encodeURI(url) String qijuType= new String(request.getParameter( ("qijuType")).getBytes("ISO-8859-1"), "utf-8");
asp.net中URL参数传值中文乱码的三种解决办法
url地址传参中文乱码处理
asp.net页面通过URL参数传值中文乱码问题解决办法
将URL中的中文字符转码,URL中不定参数
jsp使用URL编码传递中文参数乱码问题
用于中文和特殊符号路径转换,可以读取中文等一系列特殊符号
OASIS标准之OData4第2部分URL的中文译本.开放数据协议(OData)用于创建基于REST的数据服务,以便通过服务发布在数据模型中定义、经统一资源定位符(URL)标识的资源,并允许Web客户端通过简单的HTTP交互操作资源。...