• Android想服务器传图片,透过流的方式。还有读取服务器图片(文件),也通过流的方式。





    /** * Created by Administrator on 2016/7/19. */ import android.util.Log; import com.gtercn.asPolice.net.HttpsTrustManager; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.UUID; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; /** * * 上传头像工具类 * Https协议的 * @author spring sky Email:vipa1888@163.com QQ:840950105 MyName:石明政 */ public class UpdateImage { private static final String TAG = "uploadFile"; private static final int TIME_OUT = 10 * 1000; // 超时时间 private static final String CHARSET = "utf-8"; // 设置编码 /** * Android上传文具到服务端 * * @param file * 需要上传的文件 * @param RequestURL * 请求的rul * @return 返回响应的内容 */ public static String uploadFile(File file, String RequestURL) { String result = null; String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成 String PREFIX = "--", LINE_END = " "; String CONTENT_TYPE = "multipart/form-data"; // 内容类型 try { URL url = new URL(RequestURL); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setSSLSocketFactory(getSocketFactoryCertificate()); conn.setHostnameVerifier(getHostnameVerifier()); conn.setReadTimeout(TIME_OUT); conn.setConnectTimeout(TIME_OUT); conn.setDoInput(true); // 允许输入流 conn.setDoOutput(true); // 允许输出流 conn.setUseCaches(false); // 不允许使用缓存 conn.setRequestMethod("POST"); // 请求方式 conn.setRequestProperty("Charset", CHARSET); // 设置编码 conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY); conn.setRequestProperty("api-version", "1.0"); if (file != null) { /** * 当文件不为空,把文件包装并且上传 */ Log.e("======","====DataOutputStream==="); DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); StringBuffer sb = new StringBuffer(); sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINE_END); /** * 这里重点注意: name里面的值为服务端需要key 只有这个key 才可以得到对应的文件 * filename是文件的名字,包含后缀名的 比如:abc.png */ sb.append("Content-Disposition: form-data; name="avatar"; filename="" + file.getName() + """ + LINE_END); sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END); sb.append(LINE_END); dos.write(sb.toString().getBytes()); InputStream is = new FileInputStream(file); byte[] bytes = new byte[1024]; int len = 0; while ((len = is.read(bytes)) != -1) { dos.write(bytes, 0, len); } is.close(); dos.write(LINE_END.getBytes()); byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END) .getBytes(); dos.write(end_data); dos.flush(); Log.e("======","====flush==="); /** * 获取响应码 200=成功 当响应成功,获取响应的流 */ int res = conn.getResponseCode(); Log.e("========", "response code:" + res); if(res==200) { Log.e(TAG, "request success"); InputStream input = conn.getInputStream(); StringBuffer sb1 = new StringBuffer(); int ss; while ((ss = input.read()) != -1) { sb1.append((char) ss); } result = sb1.toString(); Log.e(TAG, "result : " + result); } else{ Log.e(TAG, "request error"); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } private static SSLSocketFactory getSocketFactoryCertificate(){ // String keyStoreType = "BKS"; // int keyStoreResId = R.raw.cert; try { /* CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); // cert is under R.raw.cert InputStream inputStream = ContextService.getInstance().getContext(). getResources().openRawResource(keyStoreResId);//(R.raw.cert); Certificate certificate = certificateFactory.generateCertificate(inputStream); inputStream.close(); if(keyStoreType == null || keyStoreType.length() == 0){ keyStoreType = KeyStore.getDefaultType(); } //BKS KeyStore trustStore = KeyStore.getInstance(keyStoreType); trustStore.load(null, null); trustStore.setCertificateEntry("ca",certificate); String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(trustStore); // TrustManager[] trustManagers = new TrustManager[]{new HttpsTrustManager(tmf.getTrustManagers())}; TrustManager[] trustManagers = getWrappedTrustManagers(tmf.getTrustManagers());*/ TrustManager[] trustManagers = new TrustManager[]{new HttpsTrustManager()}; SSLContext ssLContext = SSLContext.getInstance("TLS"); ssLContext.init(null, trustManagers, new SecureRandom()); return ssLContext.getSocketFactory(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } return null; } private static HostnameVerifier getHostnameVerifier() { return new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { //return true; // verify always returns true, which could cause insecure network traffic due to trusting TLS/SSL server certificates for wrong hostnames HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier(); return true;//hv.verify("localhost", session); } }; } }
    import android.util.Log;
    
    import com.gtercn.asPolice.net.HttpsTrustManager;
    
    import java.io.DataOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.security.KeyManagementException;
    import java.security.NoSuchAlgorithmException;
    import java.security.SecureRandom;
    import java.util.UUID;
    
    import javax.net.ssl.HostnameVerifier;
    import javax.net.ssl.HttpsURLConnection;
    import javax.net.ssl.SSLContext;
    import javax.net.ssl.SSLSession;
    import javax.net.ssl.SSLSocketFactory;
    import javax.net.ssl.TrustManager;
    
    /**
     *
     * 上传头像工具类
     *Http协议的
     * @author spring sky Email:vipa1888@163.com QQ:840950105 MyName:石明政
     */
    public class UpdateImage {
        private static final String TAG = "uploadFile";
        private static final int TIME_OUT = 10 * 1000; // 超时时间
        private static final String CHARSET = "utf-8"; // 设置编码
    
        /**
         * Android上传文具到服务端
         *
         * @param file
         *            需要上传的文件
         * @param RequestURL
         *            请求的rul
         * @return 返回响应的内容
         */
        public static String uploadFile(File file, String RequestURL) {
            String result = null;
            String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
            String PREFIX = "--", LINE_END = "
    ";
            String CONTENT_TYPE = "multipart/form-data"; // 内容类型
    
            try {
                URL url = new URL(RequestURL);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(TIME_OUT);
                conn.setConnectTimeout(TIME_OUT);
                conn.setDoInput(true); // 允许输入流
                conn.setDoOutput(true); // 允许输出流
                conn.setUseCaches(false); // 不允许使用缓存
                conn.setRequestMethod("POST"); // 请求方式
                conn.setRequestProperty("Charset", CHARSET); // 设置编码
                conn.setRequestProperty("connection", "keep-alive");
                conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary="
                        + BOUNDARY);
                conn.setRequestProperty("api-version", "1.0"); //请求头,根据要求要还是不要
                if (file != null) {
                    /**
                     * 当文件不为空,把文件包装并且上传
                     */
                    Log.e("======","====DataOutputStream===");
                    DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
                    StringBuffer sb = new StringBuffer();
                    sb.append(PREFIX);
                    sb.append(BOUNDARY);
                    sb.append(LINE_END);
                    /**
                     * 这里重点注意: name里面的值为服务端需要key 只有这个key 才可以得到对应的文件
                     * filename是文件的名字,包含后缀名的 比如:abc.png
                     */
                    sb.append("Content-Disposition: form-data; name="avatar"; filename=""
                            + file.getName() + """ + LINE_END);
                            sb.append("Content-Type: application/octet-stream; charset="
                                    + CHARSET + LINE_END);
                    sb.append(LINE_END);
                    dos.write(sb.toString().getBytes());
                    InputStream is = new FileInputStream(file);
                    byte[] bytes = new byte[1024];
                    int len = 0;
                    while ((len = is.read(bytes)) != -1) {
                        dos.write(bytes, 0, len);
                    }
                    is.close();
                    dos.write(LINE_END.getBytes());
                    byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)
                            .getBytes();
                    dos.write(end_data);
                    dos.flush();
                    Log.e("======","====flush===");
    
                    /**
                     * 获取响应码 200=成功 当响应成功,获取响应的流
                     */
                    int res = conn.getResponseCode();
                    Log.e("========", "response code:" + res);
                     if(res==200)
                     {
                    Log.e(TAG, "request success");
                    InputStream input = conn.getInputStream();
                    StringBuffer sb1 = new StringBuffer();
                    int ss;
                    while ((ss = input.read()) != -1) {
                        sb1.append((char) ss);
                    }
                    result = sb1.toString();
                    Log.e(TAG, "result : " + result);
                     }
                     else{
                     Log.e(TAG, "request error");
                     }
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }

    下载

    import android.util.Log;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    /**
     * Created by Administrator on 2016/7/20.
     */
    public class DownloadPicture {
        //加载图片
        public static File getdFile(String path, String filepath) throws Exception {
            URL url = new URL(path);//
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();//从网络获得链接
            connection.setRequestMethod("GET");//获得
            connection.setConnectTimeout(5000);//设置超时时间为5s
            connection.setRequestProperty("api-version", "1.0");
            if (connection.getResponseCode() == 200)//检测是否正常返回数据请求 详情参照http协议
            {
                InputStream is = connection.getInputStream();//获得输入流
                File file = new File(filepath);//新建一个file文件
                FileOutputStream fos = new FileOutputStream(file);//对应文件建立输出流
                byte[] buffer = new byte[1024];//新建缓存  用来存储 从网络读取数据 再写入文件
                int len = 0;
                while ((len = is.read(buffer)) != -1) {//当没有读到最后的时候
                    fos.write(buffer, 0, len);//将缓存中的存储的文件流秀娥问file文件
                }
                fos.flush();//将缓存中的写入file
                fos.close();
                is.close();//将输入流 输出流关闭
                Log.e("========", "++++++file++++" + file);
                return file;
            }else{
                Log.e("======","-----getResponseCode----"+connection.getResponseCode());
                return null;
            }
    
    
        }
    
    
    }
  • 相关阅读:
    Java架构师必备技能:docker使用大全
    SpringBoot+ShardingSphere彻底解决生产环境数据库字段加解密问题
    记一次最近生产环境项目中发生的两个事故及处理方法
    【Java分享客栈】一个包装过简历的新同事写完微信支付引起事故后果断离职了
    【Java分享客栈】我为什么极力推荐XXLJOB作为中小厂的分布式任务调度平台
    StandardScaler/MinMaxScaler/Normalizer
    Vue开发配置
    如何从邮箱中批量下载距离当天最近一天的邮件附件.
    JavaScript获取页面上某个元素的方法
    OI小技巧
  • 原文地址:https://www.cnblogs.com/niupi/p/5691584.html
Copyright © 2020-2023  润新知