httpConnection上传文件

from:http://blog.csdn.net/wangpeng047/article/details/38303865

/**
     * 上传文件时提交的数据格式
     -----------------------------22448196075966
	 Content-Disposition: form-data; name="access_token"
	
	 accessss
	 -----------------------------22448196075966
	 Content-Disposition: form-data; name="type"
	
	 变量值
     -----------------------------22448196075966
     Content-Disposition: form-data; name="file"; filename="s.txt"
     Content-Type: application/octet-stream

     文件内容
     -----------------------------22448196075966--
     */
    public static void uploadImage(String requestUrl,File  file,String requestMethod) throws IOException{
		//分割符
    	String boundary="-----------------------------32034106127045";
    	String boundary2="-------------------------------32034106127045";
		//换行符
    	String enter="\r\n";
    	URL url = new URL(requestUrl);
        HttpURLConnection httpUrlConn = (HttpURLConnection)url.openConnection();
        httpUrlConn.setDoOutput(true);
        httpUrlConn.setDoInput(true);
        //设置请求头
        httpUrlConn.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);
        httpUrlConn.setRequestMethod(requestMethod);
        OutputStream outputStream = httpUrlConn.getOutputStream();
        
        StringBuilder sb=new StringBuilder();
        sb.append(boundary2);
        sb.append(enter);
        String disponsition="Content-Disposition: form-data; name=\"file\"; filename=\""+file.getName()+"\"";
        sb.append(disponsition);
        sb.append(enter);
        //更具不同的类型经行设置
        sb.append("Content-Type: audio/wav");
        sb.append(enter);
        sb.append(enter);
        outputStream.write(sb.toString().getBytes());
        byte[] b=new byte[1024];
        BufferedInputStream in=new  BufferedInputStream(new FileInputStream(file)) ;
        int c=-1;
        while((c=in.read(b))!=-1){
        	 outputStream.write(b,0,c);
        }
        in.close();
        outputStream.write(enter.getBytes());
        outputStream.write((boundary2+"--").getBytes());
        outputStream.close();
        
        
        StringBuffer buffer=new StringBuffer();
        InputStream inputStream = httpUrlConn.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(
            inputStream, "utf-8");
        BufferedReader bufferedReader = new BufferedReader(
            inputStreamReader);

        String str = null;
        while ( (str = bufferedReader.readLine()) != null)
        {
            buffer.append(str);
        }
        bufferedReader.close();
        inputStreamReader.close();
        // 释放资源
        inputStream.close();
        inputStream = null;
        httpUrlConn.disconnect();
        System.out.println(buffer);
        
        FileOutputStream fileOut=new FileOutputStream("c:\\sdf.txt");
        fileOut.write(buffer.toString().getBytes());
        fileOut.close();
	}

你可能感兴趣的:(httpConnection上传文件)