【问题标题】:How to fetch image from local server with Volley如何使用 Volley 从本地服务器获取图像
【发布时间】:2017-05-09 06:15:24
【问题描述】:

我可以通过 volley (http url) 成功获取图像

但我想要的是从本地服务器(windows pc)获取图像。它的 url 就像 file://PCname/....

错误是 ftpurlconnection 类不能转换为 httpurlconnection 类。

这是用于 http 的类:

public class HurlStack implements HttpStack {
    private static final String HEADER_CONTENT_TYPE = "Content-Type";
    private final HurlStack.UrlRewriter mUrlRewriter;
    private final SSLSocketFactory mSslSocketFactory;

    public HurlStack() {
        this((HurlStack.UrlRewriter)null);
    }

    public HurlStack(HurlStack.UrlRewriter urlRewriter) {
        this(urlRewriter, (SSLSocketFactory)null);
    }

    public HurlStack(HurlStack.UrlRewriter urlRewriter, SSLSocketFactory sslSocketFactory) {
        this.mUrlRewriter = urlRewriter;
        this.mSslSocketFactory = sslSocketFactory;
    }

    public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError {
        String url = request.getUrl();
        HashMap map = new HashMap();
        map.putAll(request.getHeaders());
        map.putAll(additionalHeaders);
        if(this.mUrlRewriter != null) {
            String parsedUrl = this.mUrlRewriter.rewriteUrl(url);
            if(parsedUrl == null) {
                throw new IOException("URL blocked by rewriter: " + url);
            }

            url = parsedUrl;
        }

        URL parsedUrl1 = new URL(url);
        HttpURLConnection connection = this.openConnection(parsedUrl1, request);
        Iterator protocolVersion = map.keySet().iterator();

        while(protocolVersion.hasNext()) {
            String responseCode = (String)protocolVersion.next();
            connection.addRequestProperty(responseCode, (String)map.get(responseCode));
        }

        setConnectionParametersForRequest(connection, request);
        ProtocolVersion protocolVersion1 = new ProtocolVersion("HTTP", 1, 1);
        int responseCode1 = connection.getResponseCode();
        if(responseCode1 == -1) {
            throw new IOException("Could not retrieve response code from HttpUrlConnection.");
        } else {
            BasicStatusLine responseStatus = new BasicStatusLine(protocolVersion1, connection.getResponseCode(), connection.getResponseMessage());
            BasicHttpResponse response = new BasicHttpResponse(responseStatus);
            response.setEntity(entityFromConnection(connection));
            Iterator i$ = connection.getHeaderFields().entrySet().iterator();

            while(i$.hasNext()) {
                Entry header = (Entry)i$.next();
                if(header.getKey() != null) {
                    BasicHeader h = new BasicHeader((String)header.getKey(), (String)((List)header.getValue()).get(0));
                    response.addHeader(h);
                }
            }

            return response;
        }
    }

    private static HttpEntity entityFromConnection(HttpURLConnection connection) {
        BasicHttpEntity entity = new BasicHttpEntity();

        InputStream inputStream;
        try {
            inputStream = connection.getInputStream();
        } catch (IOException var4) {
            inputStream = connection.getErrorStream();
        }

        entity.setContent(inputStream);
        entity.setContentLength((long)connection.getContentLength());
        entity.setContentEncoding(connection.getContentEncoding());
        entity.setContentType(connection.getContentType());
        return entity;
    }

    protected HttpURLConnection createConnection(URL url) throws IOException {
        return (HttpURLConnection)url.openConnection();
    }

    private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
        HttpURLConnection connection = this.createConnection(url);
        int timeoutMs = request.getTimeoutMs();
        connection.setConnectTimeout(timeoutMs);
        connection.setReadTimeout(timeoutMs);
        connection.setUseCaches(false);
        connection.setDoInput(true);
        if("https".equals(url.getProtocol()) && this.mSslSocketFactory != null) {
            ((HttpsURLConnection)connection).setSSLSocketFactory(this.mSslSocketFactory);
        }

        return connection;
    }

    static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError {
        switch(request.getMethod()) {
        case -1:
            byte[] postBody = request.getPostBody();
            if(postBody != null) {
                connection.setDoOutput(true);
                connection.setRequestMethod("POST");
                connection.addRequestProperty("Content-Type", request.getPostBodyContentType());
                DataOutputStream out = new DataOutputStream(connection.getOutputStream());
                out.write(postBody);
                out.close();
            }
            break;
        case 0:
            connection.setRequestMethod("GET");
            break;
        case 1:
            connection.setRequestMethod("POST");
            addBodyIfExists(connection, request);
            break;
        case 2:
            connection.setRequestMethod("PUT");
            addBodyIfExists(connection, request);
            break;
        case 3:
            connection.setRequestMethod("DELETE");
            break;
        case 4:
            connection.setRequestMethod("HEAD");
            break;
        case 5:
            connection.setRequestMethod("OPTIONS");
            break;
        case 6:
            connection.setRequestMethod("TRACE");
            break;
        case 7:
            addBodyIfExists(connection, request);
            connection.setRequestMethod("PATCH");
            break;
        default:
            throw new IllegalStateException("Unknown method type.");
        }

    }

    private static void addBodyIfExists(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError {
        byte[] body = request.getBody();
        if(body != null) {
            connection.setDoOutput(true);
            connection.addRequestProperty("Content-Type", request.getBodyContentType());
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(body);
            out.close();
        }

    }

    public interface UrlRewriter {
        String rewriteUrl(String var1);
    }
}

我改变了什么,但失败了:

public class HurlStackFtp extends HurlStack {

    @Override
    public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
            throws IOException, AuthFailureError {

        String urlString = request.getUrl();
        if (urlString != null && urlString.startsWith("file://")) {
            return performFTPRequest(request, additionalHeaders);
        } else {
            return super.performRequest(request, additionalHeaders);
        }
    }


    public HttpResponse performFTPRequest(Request<?> request, Map<String, String> additionalHeaders)
            throws IOException, AuthFailureError {
        String url = request.getUrl();
        HashMap<String, String> map = new HashMap<String, String>();
        map.putAll(request.getHeaders());
        map.putAll(additionalHeaders);
        // UrlRewriter not supported

        InputStream input = getStreamFromFTP(url);
        StatusLine responseStatus = new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1),
                /*connection.getResponseCode()*/200, /*connection.getResponseMessage()*/"OK");
        BasicHttpResponse response = new BasicHttpResponse(responseStatus);
        response.setEntity(makeEntity(input));
        return response;
    }

    public static InputStream getStreamFromFTP(String url) throws IOException {
        URL parsedUrl = new URL(url);
        URLConnection cn = parsedUrl.openConnection();
        cn.connect();
        return cn.getInputStream();
    }

    private static HttpEntity makeEntity(InputStream inputStream) throws IOException {
        BasicHttpEntity entity = new BasicHttpEntity();
        entity.setContent(inputStream);
        entity.setContentLength(inputStream.available());
        entity.setContentType("binary/octet-stream"); // sigh...
        return entity;
    }
}

【问题讨论】:

    标签: android image ftp android-volley


    【解决方案1】:

    您使用的网址是 file:/myserver.com/DvpvklR.png 您将无法在您的模拟器或设备中访问它,因为在这两种情况下操作系统都不同,模拟器(虚拟机的种类),设备(单独的机器),所以在任何情况下都是不可能的。 为了使它成为可能,您需要在本地计算机上安装一些服务器(Tomcat、Apache 或在 Windows IIS 中)并将您的图像放在相应的服务器中,但是从您的 Android 访问时,您必须使用计算机的本地 IP http://l192.168.100.6 指的是设备本身。

    您可以通过在命令行中输入 ipconfig 来查看您的 IP。

    【讨论】:

    • 我做了所有这些,而且效果很好。我可以从本地数据库中获取文本,问题只是图像 url 我无法从 http 访问它。它在windows pc共享位置的硬盘中
    • 是图像的路径是静态的还是您从数据库中获取它,如果是,您可以告诉我您获取它的方式。以及您使用的是哪个服务器?
    • 图像路径是静态的,我想从 Windows pc 获取该图像,它的 url 类似于 file://192.168.1.20/a.jpg
    • 如果您是通过 HTTP 获取它,那么问题出在哪里,继续使用它。无论如何,您仍然想使用 FTP,那么我猜 ftp 需要凭据才能与该机器建立连接,因此您必须提供该东西,只有这样您才能实现您想要的,这里有一些链接可能帮你codejava.net/java-se/networking/ftp/…codejava.net/java-se/networking/ftp/…
    【解决方案2】:

    使用适用于 Android 的 PICASSO 库。

    http://square.github.io/picasso/

    例子:

    1) 如果它的 URL (Server Image) 那么

    Picasso.with(context).load("http:/myserver.com/DvpvklR.png").into(imageView);

    2)如果它的URI(本地图像)那么

    文件 f = 新文件(uri)

    Picasso.with(getActivity()).load(f).into(imageView);

    【讨论】:

    • 我要加载的url是file:/myserver.com/DvpvklR.png
    • 是URI还是URL?
    • 它不起作用。图片是从 http url 获取的,而不是从 ftp:// 或 file://
    猜你喜欢
    • 2015-05-15
    • 1970-01-01
    • 1970-01-01
    • 2017-06-28
    • 2017-02-03
    • 1970-01-01
    • 2020-12-27
    • 1970-01-01
    • 2021-12-17
    相关资源
    最近更新 更多