1

我需要在我的 android 应用程序中显示图像。问题是我想从网上的某个地方获取这张图片。网址是这样的:

http://www.mydomain.com/hello world image.png

如您所见,图像名称中包含一些空格。每次我执行我的代码时,这都会向我显示 FileNotFound 异常。什么也没有发生。

以下是我的代码

String imagePathCon = "hello world image.png";      
String imagePath = "http://www.mydomain.com/" + imagePathCon;
try {
  URL url;
  url = new URL(imagePath);

  // url = new URL("http://www.azuma-kinba.com/wp-content/uploads/2012/05/Android-Make-Google-Loss-in-2010.png");

  InputStream content = (InputStream)url.getContent();
  Drawable d = Drawable.createFromStream(content , "src"); 
  im.setImageDrawable(d);

 } catch (MalformedURLException e) {
            e.printStackTrace();
 } catch (IOException e) {
            e.printStackTrace();
 }

我用“+”替换空格,但没有任何反应。

4

4 回答 4

3

这将起作用。

String imagePathCon = "hello world image.png";   
imagePathCon=imagePathCon.replaceAll(" ", "%20");

String imagePath = "http://www.mydomain.com/" + imagePathCon;

你必须知道http://en.wikipedia.org/wiki/Percent-encoding#Character_data

于 2012-06-08T07:03:44.020 回答
3

请使用正确的 URL 来获取图像并使用下面的代码,这些代码肯定会帮助你......

使用...替换 URL 的空间

  imagePath=imagePath.replaceAll(" ", "%20");

现在...

         HttpGet httpRequest = new HttpGet(new URL(params[0]).toURI());
         HttpClient httpClient = new DefaultHttpClient();
         HttpResponse response = (HttpResponse) httpClient.execute(httpRequest);
         HttpEntity entity = response.getEntity();
         BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity); 
             InputStream is = bufHttpEntity.getContent();
        //image_value = new URL("image Url is here");
            bm = BitmapFactory.decodeStream(new FlushedInputStream(is));
    //imageLoader is object of iamge view
           imageLoader.setImageBitmap(bm);
于 2012-06-08T07:05:55.200 回答
0

您需要对路径进行 url 编码,如下所示:

String imagePathCon = URLEncoder.encode("hello world image.png", "UTF-8");
于 2012-06-08T06:58:49.663 回答
0

您还可以使用 http get 请求:最简单的方法是简单地调用 URLEncoder,它会自动将字符串中的所有字符替换为 url 编码格式。

HttpParams httpParameters = new BasicHttpParams(); 
HttpConnectionParams.setConnectionTimeout(httpParameters, 30000); 
HttpConnectionParams.setSoTimeout(httpParameters, 30000);
HttpClient httpclient = new DefaultHttpClient(httpParameters); 
HttpGet httpGet = new HttpGet(URLEncoder.encode(url, "UTF-8"));
HttpResponse httpResponse = httpclient.execute(httpGet); 
in = httpResponse.getEntity().getContent(); 
//Bitmap bmp = BitmapFactory.decodeStream(instream); 
//create a bitmap or an image from the input stream
于 2012-06-08T07:08:22.757 回答