httpclient下载图片转base64

    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.methods.GetMethod;
    import org.apache.commons.codec.binary.Base64;

    public static void main(String[] args)throws Exception {
        HttpClient client = new HttpClient();
        GetMethod get = new GetMethod("http://pic2.ooopic.com/12/22/94/30b1OOOPIC5c.jpg");
        client.executeMethod(get);
        File storeFile = File.createTempFile("temp",null);
        FileOutputStream output = new FileOutputStream(storeFile);
        output.write(get.getResponseBody());
        output.close();
        System.out.println(Base64Utils.fileToBase64(storeFile));
        storeFile.delete();
    }
    public static String fileToBase64(File file) throws Exception {
        byte[] data = new byte[0];
        if (file.exists()) {
            FileInputStream in = new FileInputStream(file);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] cache = new byte[1024];
            int nRead = 0;
            while ((nRead = in.read(cache)) != -1) {
                out.write(cache, 0, nRead);
                out.flush();
            }
            out.close();
            in.close();
            data = out.toByteArray();
        }
        return new Base64().encodeToString(data);
    }

你可能感兴趣的:(Java)