java http简易调试工具类的小代码

以前做安卓时候写的一个小文件上传工具类,代码如下

FileType类:
package com.community.app.utils;

public enum FileType {

	IMAGE,BINARY;
}

FileUploadUtils类:
package com.community.app.utils;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;


import com.community.app.AppContext;

import android.os.Handler;
import android.os.Message;
import android.support.annotation.MainThread;

/**
 * Created by lxl on 16-1-23.
 * Updated by lxl on 16-4-17
 */
public class FileUploadUtils {
	
	public interface onResponse{
		public void onSuccess(String response);
		public void onFailure(Throwable throwable);
	}

	
	public static class EntityFile{
		private String file_name;
		private File file_file;
		private FileType file_type;
		
		
		public FileType getFile_type() {
			return file_type;
		}
		public void setFile_type(FileType file_type) {
			this.file_type = file_type;
		}
		public EntityFile(String file_name, File file_file,FileType file_type) {
			super();
			this.file_name = file_name;
			this.file_file = file_file;
			this.file_type=file_type;
		}
		public String getFile_name() {
			return file_name;
		}
		public void setFile_name(String file_name) {
			this.file_name = file_name;
		}
		public File getFile_file() {
			return file_file;
		}
		public void setFile_file(File file_file) {
			this.file_file = file_file;
		}
		
	}
	
	
	/**
	 * 
	 * @param url 上传url
	 * @param params 表单参数
	 * @param files 上传文件参数
	 * @param callback 回调
	 */
	@MainThread
    public static void upload( final String url, final Map<String, String> params, final List<EntityFile> files,final onResponse callback) {

    	class InnerHanlder extends Handler{
    		
    		
    		@Override
    		public void handleMessage(Message msg) {
    			
    			switch (msg.what) {
				//success
    			case 0:
					callback.onSuccess(msg.obj.toString());
					break;
				//err
    			case -1:
    				callback.onFailure((Throwable) msg.obj);
    				break;
				default:
					break;
				}
    			
    		}
    	}
    	
    	final InnerHanlder mHanlder=new InnerHanlder();
    	
    	
        new Thread(new Runnable() {
            @Override
            public void run() {

                try {

                    


                    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
                    connection.setRequestMethod("POST");

                    String BOUNDARY = "------------ksardtyyuioip";
                    // 如果有参数内容
                    if (params != null && !params.isEmpty()) {
                        connection.setRequestProperty("Charsert", "UTF-8");
                        connection.setRequestProperty("Content-Type",
                                "multipart/form-data; boundary=" + BOUNDARY);
                        Iterator<Map.Entry<String, String>> ie = params.entrySet()
                                .iterator();
                        StringBuilder pstr = new StringBuilder();

                        while (ie.hasNext()) {
                            Map.Entry<String, String> item = ie.next();
                            pstr.append("--")
                                    .append(BOUNDARY)
                                    .append("\r\n")
                                    .append("Content-Disposition: form-data; name=\"")
                                    .append(item.getKey()).append("\"")
                                    .append("\r\n\r\n").append(item.getValue())
                                    .append("\r\n");
                        }
                        connection.setDoInput(true);
                        connection.setDoOutput(true);
                        connection.getOutputStream().write(
                                pstr.toString().getBytes("utf-8"));
                        byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n")
                        		.getBytes();// 定义最后数据分隔线

                        // 如果有文件要上传
                        if (files != null && !files.isEmpty()) {

//					connection.setRequestProperty("connection", "Keep-Alive");
                            OutputStream out = new DataOutputStream(
                                    connection.getOutputStream());


                           for(EntityFile entityFile:files){
                               //
                        	   
                        	   //图片压缩一下 反正是子线程 不怕anr
                        	   
//                        	   entityFile.setFile_file(new File(BitmapHelper.compressBitmap(AppContext.context, entityFile.getFile_file().getAbsolutePath(), 600, 800, false)));
                        	   if(entityFile.getFile_type()==FileType.IMAGE){
                        		   //如果文件时图片 就压缩一下
                        		   File file=File.createTempFile(UUID.randomUUID().toString(),null,AppContext.context.getCacheDir());
//                        	   		NativeUtil.compress(entityFile.getFile_file(), file, 70);
                        		   BitmapHelper.parseBitmapToSize(entityFile.getFile_file(), file, 800);
                        	   		entityFile.setFile_file(file);
                        	   }
                                StringBuilder sb = new StringBuilder();
                                sb.append("--");
                                sb.append(BOUNDARY);
                                sb.append("\r\n");
                                sb.append("Content-Disposition: form-data;name=\""
                                        + entityFile.getFile_name() + "\";filename=\""
                                        + entityFile.getFile_name() + "\"\r\n");
                                sb.append("Content-Type:application/octet-stream\r\n\r\n");

                                byte[] data = sb.toString().getBytes();
                                out.write(data);
                                DataInputStream in = new DataInputStream(
                                        new FileInputStream(entityFile.getFile_file()));
                                int bytes = 0;
                                byte[] bufferOut = new byte[8196];
                                while ((bytes = in.read(bufferOut)) != -1) {
                                    out.write(bufferOut, 0, bytes);
                                }
                                out.write("\r\n".getBytes()); // 多个文件时,二个文件之间加入这个
                                in.close();
                            }

                        }
                        connection.getOutputStream().write(end_data);
                        connection.getOutputStream().flush();
                        connection.getOutputStream().close();

                    }


                    if (connection.getResponseCode() == 200) {
                        InputStream inputStream = connection.getInputStream();

                        int len = 0;
                        byte[] buffer = new byte[4096];
                        final ByteArrayOutputStream stream = new ByteArrayOutputStream();
                        while (-1 != (len = inputStream.read(buffer))) {
                            stream.write(buffer, 0, len);
                        }
                        final String result = new String(stream.toByteArray());
                        
                        Message message=Message.obtain();
                        message.obj=result;
                        message.what=0;
                        mHanlder.sendMessage(message);
                          


                    } else {
                    	  Message message=Message.obtain();
                          message.obj= new RuntimeException("网络响应失败");
                          message.what=-1;
                          mHanlder.sendMessage(message);


                    }

                }catch (final Exception e){
                    e.printStackTrace();
                    Message message=Message.obtain();
                    message.obj= e; 
                    message.what=-1;
                   mHanlder.sendMessage(message);

                }
                /


            }
        }).start();


    }


}




现在做java  有时候需要用到传文件等测试场景  除了写一个表单测试 也可以用代码测试:



package com.lxldev.utils;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.Map;





/**
 * Created by lxl on 16-1-23.
 * Updated by lxl on 16-4-17
 */
public class FileUploadUtils {
    
    
    public interface onResponse{
        public void onSuccess(String response);
        public void onFailure(Throwable throwable);
    }

    
    public static class EntityFile{
        private String file_name;
        private File file_file;
        
        
        public EntityFile(String file_name, File file_file ) {
            super();
            this.file_name = file_name;
            this.file_file = file_file;
        }
        public String getFile_name() {
            return file_name;
        }
        public void setFile_name(String file_name) {
            this.file_name = file_name;
        }
        public File getFile_file() {
            return file_file;
        }
        public void setFile_file(File file_file) {
            this.file_file = file_file;
        }
        
    }
    
    
    /**
     *
     * @param url 上传url
     * @param params 表单参数
     * @param files 上传文件参数
     * @param callback 回调
     */
    public static void upload( final String url, final Map<String, String> params, final List<EntityFile> files,final onResponse callback) {

        new Thread(new Runnable() {
            @Override
            public void run() {

                try {

                   


                    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
                    connection.setRequestMethod("POST");

                    String BOUNDARY = "------------ksardtyyuioip";
                    // 如果有参数内容
                    if (params != null && !params.isEmpty()) {
                        connection.setRequestProperty("Charsert", "UTF-8");
                        connection.setRequestProperty("Content-Type",
                                "multipart/form-data; boundary=" + BOUNDARY);
                        Iterator<Map.Entry<String, String>> ie = params.entrySet()
                                .iterator();
                        StringBuilder pstr = new StringBuilder();

                        while (ie.hasNext()) {
                            Map.Entry<String, String> item = ie.next();
                            pstr.append("--")
                                    .append(BOUNDARY)
                                    .append("\r\n")
                                    .append("Content-Disposition: form-data; name=\"")
                                    .append(item.getKey()).append("\"")
                                    .append("\r\n\r\n").append(item.getValue())
                                    .append("\r\n");
                        }
                        connection.setDoInput(true);
                        connection.setDoOutput(true);
                        connection.getOutputStream().write(
                                pstr.toString().getBytes("utf-8"));
                        byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n")
                                .getBytes();// 定义最后数据分隔线

                        // 如果有文件要上传
                        if (files != null && !files.isEmpty()) {

//                    connection.setRequestProperty("connection", "Keep-Alive");
                            OutputStream out = new DataOutputStream(
                                    connection.getOutputStream());


                           for(EntityFile entityFile:files){
                               //
                               
                               //图片压缩一下 反正是子线程 不怕anr
                               
//                               entityFile.setFile_file(new File(BitmapHelper.compressBitmap(AppContext.context, entityFile.getFile_file().getAbsolutePath(), 600, 800, false)));
                              /* if(entityFile.getFile_type()==FileType.IMAGE){
                                   //如果文件时图片 就压缩一下
                                   File file=File.createTempFile(UUID.randomUUID().toString(),null,AppContext.context.getCacheDir());
//                                       NativeUtil.compress(entityFile.getFile_file(), file, 70);
                                   BitmapHelper.parseBitmapToSize(entityFile.getFile_file(), file, 800);
                                       entityFile.setFile_file(file);
                               }*/
                                StringBuilder sb = new StringBuilder();
                                sb.append("--");
                                sb.append(BOUNDARY);
                                sb.append("\r\n");
                                sb.append("Content-Disposition: form-data;name=\""
                                        + entityFile.getFile_name() + "\";filename=\""
                                        + entityFile.getFile_name() + "\"\r\n");
                                sb.append("Content-Type:application/octet-stream\r\n\r\n");

                                byte[] data = sb.toString().getBytes();
                                out.write(data);
                                DataInputStream in = new DataInputStream(
                                        new FileInputStream(entityFile.getFile_file()));
                                int bytes = 0;
                                byte[] bufferOut = new byte[8196];
                                while ((bytes = in.read(bufferOut)) != -1) {
                                    out.write(bufferOut, 0, bytes);
                                }
                                out.write("\r\n".getBytes()); // 多个文件时,二个文件之间加入这个
                                in.close();
                            }

                        }
                        connection.getOutputStream().write(end_data);
                        connection.getOutputStream().flush();
                        connection.getOutputStream().close();

                    }


                    if (connection.getResponseCode() == 200) {
                        InputStream inputStream = connection.getInputStream();

                        int len = 0;
                        byte[] buffer = new byte[4096];
                        final ByteArrayOutputStream stream = new ByteArrayOutputStream();
                        while (-1 != (len = inputStream.read(buffer))) {
                            stream.write(buffer, 0, len);
                        }
                        final String result = new String(stream.toByteArray());
                       
                        callback.onSuccess(result);

                    } else {
                          callback.onFailure( new RuntimeException("网络响应失败"));

                    }

                }catch (final Exception e){
//                    e.printStackTrace();
                    callback.onFailure(e);
                }
                /


            }
        }).start();


    }


}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值