【问题标题】:Download image from Android using HttpConnection got 410, but postman got 200使用 HttpConnection 从 Android 下载图像得到 410,但邮递员得到 200
【发布时间】:2020-04-17 04:46:11
【问题描述】:

我在 Android 中下载图像时遇到问题。

有问题的图片链接: https://via.placeholder.com/150/92c952

我可以使用邮递员成功下载图像(200)。 但是当我使用 HttpConnection 在 Android 中编码时,它会以错误状态代码 410 响应我。 (然后触发 FileNotFounedException。)

下面是我的代码,


        URL url = new URL(fileURL);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        int responseCode = httpConn.getResponseCode();

        // always check HTTP response code first
        if (responseCode == HttpURLConnection.HTTP_OK) {
            String fileName = "";
            String disposition = httpConn.getHeaderField("Content-Disposition");
            String contentType = httpConn.getContentType();
            int contentLength = httpConn.getContentLength();

            if (disposition != null) {
                // extracts file name from header field
                int index = disposition.indexOf("filename=");
                if (index > 0) {
                    fileName = disposition.substring(index + 10,
                            disposition.length() - 1);
                }
            } else {
                // extracts file name from URL
                fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
                        fileURL.length());
            }

            System.out.println("Content-Type = " + contentType);
            System.out.println("Content-Disposition = " + disposition);
            System.out.println("Content-Length = " + contentLength);
            System.out.println("fileName = " + fileName);

            // opens input stream from the HTTP connection
            InputStream inputStream = httpConn.getInputStream();

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

            int bytesRead = -1;
            byte[] buffer = new byte[1024];
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            outputStream.close();
            inputStream.close();

            System.out.println("File downloaded");
            httpConn.disconnect();
            return outputStream.toByteArray();
        } else {
            httpConn.disconnect();
            throw new RuntimeException("Error code: " + responseCode);
        }

我的代码可以从 Imgur 成功下载图片,但是这个链接失败了。

请分享任何想法,我非常感谢!

【问题讨论】:

    标签: java android https httpconnection


    【解决方案1】:

    原因很简单。

    原因不在您的 Java 程序端,而是在服务器端。

    服务器通过回复HTTP 410 Gone 拒绝您的连接。

    要避开服务器的行为,只需在执行实际请求之前在您的请求中设置任何流行的User-Agent 字符串。

    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
    httpCon.setRequestProperty(
        "User-Agent",
        "Mozilla/5.0 (Macintosh; U; Intel Mac OS X; ja-JP-mac; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6"
    );
    int responseCode = httpConn.getResponseCode();
    ...
    

    【讨论】:

      【解决方案2】:

      如果您想下载图片并在ImageView 上显示,您可以使用glidepicasso。它很容易实现,在滑行时你就可以

      Glide.with(context).load("https://via.placeholder.com/150/92c952").into(myImageView);
      

      【讨论】:

        【解决方案3】:

        使用此方法从 URL 下载图片

        // DownloadImage AsyncTask
            private class DownloadImage extends AsyncTask<String, Void, Bitmap> {
        
                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
        
                }
        
                @Override
                protected Bitmap doInBackground(String... URL) {
        
                    String imageURL = URL[0];
        
                    Bitmap bitmap = null;
                    try {
                        // Download Image from URL
                        InputStream input = new java.net.URL(imageURL).openStream();
                        // Decode Bitmap
                        bitmap = BitmapFactory.decodeStream(input);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return bitmap;
                }
        
                @Override
                protected void onPostExecute(Bitmap result) {
        

        // 将此位图设置为图像视图 // 现在使用此位图将图像保存在内存中,我保存在内存中

                        if (result != null) {
                            File destination = new File(getActivity().getCacheDir(),
                                    "profile" + ".jpg");
                            try {
                                destination.createNewFile();
                                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                                result.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
                                byte[] bitmapdata = bos.toByteArray();
        
                                FileOutputStream fos = new FileOutputStream(destination);
                                fos.write(bitmapdata);
                                fos.flush();
                                fos.close();
                                selectedFile = destination;
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
        
        
        
                }
            }
        

        现在像这样调用这个方法

        new DownloadImage().execute("https://via.placeholder.com/150/92c952");
        

        【讨论】:

          猜你喜欢
          • 2018-11-05
          • 2018-09-04
          • 2014-08-03
          • 1970-01-01
          • 2020-02-09
          • 2019-09-06
          • 2019-06-12
          • 2020-11-25
          • 2021-03-10
          相关资源
          最近更新 更多