java 模拟request

本文介绍了一个使用Java实现的HTTP文件上传类HttpRequestMaker。该类通过multipart/form-data格式发送包含文件和参数的POST请求。文章详细展示了如何添加文件和参数到请求中,并提供了完整的上传过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

   1. import java.io.BufferedInputStream;  
   2. import java.io.ByteArrayOutputStream;  
   3. import java.io.DataOutputStream;  
   4. import java.io.File;  
   5. import java.io.FileInputStream;  
   6. import java.io.InputStream;  
   7. import java.net.URL;  
   8. import java.net.URLConnection;  
   9. import java.util.ArrayList;  
  10. import java.util.Collection;  
  11. import java.util.HashMap;  
  12. import java.util.Iterator;  
  13. import java.util.Map;  
  14.   
  15. public class HttpRequestMaker{  
  16.     public HttpRequestMaker( String url ) throws Exception {  
  17.         m_Url = new URL( url );  
  18.     }  
  19.   
  20.     public final static String boundary = "---------------------------7d71b526e00e4";  
  21.     public final static String prefix = "--";  
  22.     public final static String newLine = "\r\n";  
  23.       
  24.     public final static String fileContentType = "Content-Type: application/octet-stream\r\n\r\n";  
  25.     public final static String fileContentDisposition = "Content-Disposition: form-data; name=\"%name\"; filename=\"%fileName\"\r\n";  
  26.     public final static String paramContentDisposition = "Content-Disposition: form-data; name=\"%name\"\r\n\r\n";  
  27.       
  28.     private URL m_Url = null;  
  29.     private URLConnection uc = null;  
  30.     private Map m_fileMap = new HashMap();  
  31.     private Map m_paraMap = new HashMap();  
  32.     long m_FileTotalSize = 0;  
  33.   
  34.     public void AddFile(String name, String filename){  
  35.         File file = new File( filename );  
  36.         if( file.exists() ){  
  37.           m_FileTotalSize += file.length();  
  38.           m_fileMap.put(name, file);  
  39.         }  
  40.     }  
  41.       
  42.     public void AddFile(String name, File file){  
  43.         if( file.exists() ){  
  44.           m_FileTotalSize += file.length();  
  45.           m_fileMap.put(name, file);  
  46.         }  
  47.     }  
  48.       
  49.     public void AddParam( String name, String value){  
  50.         m_FileTotalSize += value.length();  
  51.         m_paraMap.put(name, value);  
  52.     }  
  53.   
  54.     public void Upload() throws Exception {  
  55.         try{  
  56.             uc = m_Url.openConnection();  
  57.             uc.setDoOutput( true );  
  58.             uc.setRequestProperty( "Accept", "*/*" );  
  59.             uc.setRequestProperty( "Accept-Language", "ja" );  
  60.             uc.setRequestProperty( "Content-Type", "multipart/form-data; boundary=" + boundary);  
  61.             uc.setRequestProperty( "Accept-Encoding", "gzip, deflate" );  
  62.             uc.setRequestProperty( "Connection", "Keep-Alive" );  
  63.             uc.setRequestProperty( "Cache-Control", "no-cache" );  
  64.   
  65.             DataOutputStream dos = new DataOutputStream( uc.getOutputStream() );  
  66.   
  67.             for(Iterator iterator = m_fileMap.keySet().iterator(); iterator.hasNext();){  
  68.                 String key = (String)iterator.next();  
  69.                 File file = (File)m_fileMap.get(key);  
  70.                 String fcd = fileContentDisposition.replaceAll("%name", key);  
  71.                 fcd = fcd.replaceAll("%fileName", file.getName());  
  72.               
  73.                 dos.writeBytes(prefix + boundary + newLine);  
  74.                 dos.writeBytes(fcd);  
  75.                 dos.writeBytes(fileContentType);  
  76.               
  77.                 FileInputStream fstram = new FileInputStream(file);  
  78.                 byte[] buf = new byte[4000];  
  79.                 int len = 0;  
  80.                 while (len != -1) {  
  81.                     len = fstram.read(buf);  
  82.                     if(len>0){  
  83.                         dos.write(buf, 0, len);  
  84.                     }  
  85.                 }  
  86.                 dos.writeBytes(newLine);  
  87.                 fstram.close();  
  88.             }  
  89.             
  90.             for(Iterator iterator = m_paraMap.keySet().iterator();iterator.hasNext();){  
  91.                 String key = (String)iterator.next();  
  92.                 String value = (String)m_paraMap.get(key);  
  93.                 
  94.                 String fcd = paramContentDisposition.replaceAll("%name", key);  
  95.                 dos.writeBytes(prefix + boundary + newLine);  
  96.                 dos.writeBytes(fcd);  
  97.                 dos.writeBytes(value);  
  98.                 dos.writeBytes(newLine);  
  99.             }  
 100.             
 101.             dos.writeBytes(prefix + boundary + prefix + newLine);  
 102.   
 103.             dos.close();  
 104.         }  
 105.         catch(Exception e){  
 106.             e.printStackTrace();  
 107.             throw e;  
 108.         }  
 109.     }  
 110.   
 111.     public InputStream getInputStream() throws Exception{  
 112.         if(uc==null){  
 113.           return null;  
 114.         }  
 115.         return uc.getInputStream();  
 116.     }  
 117.       
 118.     public static void main(String[] args) throws Exception {  
 119.           
 120.         HttpFileUpoad  httpRequestMaker= new HttpFileUpoad("http://192.168.1.117:8080/test");  
 121.         httpRequestMaker.AddFile("file0", "c:/work/test0.xml");  
 122.         httpRequestMaker.AddFile("file1", "c:/work/test1.xml");  
 123.         httpRequestMaker.AddParam("p1", "testvalue");  
 124.         httpRequestMaker.Upload();  
 125.         InputStream is = httpRequestMaker.getInputStream(); //  
 126.         BufferedInputStream bis = new BufferedInputStream(is);    
 127.         ByteArrayOutputStream baos = new ByteArrayOutputStream();  
 128.         int i = 0;  
 129.         while((i = bis.read()) != -1){  
 130.               baos.write(i);  
 131.         }  
 132.         System.out.println(baos.toString());  
 133.   
 134.         bis.close();  
 135.         is.close();  
 136.     }  
 137.       
 138.     /**  
 139.      *   
 140.      * @param timeout  
 141.      */  
 142.     public void setReadTimeout(int timeout){  
 143.         if(uc == null){  
 144.             return;  
 145.         }  
 146.         uc.setReadTimeout(timeout);  
 147.     }  
 148. }  
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值