httpclient 针对文件和流的处理


http://www.cnblogs.com/chinareny2k/archive/2010/03/22/1691624.html

http://hi.baidu.com/846492130/item/b2c0ab71cdd2844cee1e5386


httpclient模拟form表单/post提交文件

该方法需要的jar包 commons-codec-1.4.jar       commons-httpclient-3.1.jar           commons-logging-1.1.1.jar

以上各包 均可在apache上下载 或 用maven 下载

 

File f = new File("device1.png");
PostMethod filePost = new PostMethod(
        "
Part[] parts = { new FilePart("filename", f) ,new StringPart("name1","value"),new StringPart("name2","value","")};
filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost
        .getParams()));
HttpClient clients = new HttpClient();

int status = clients.executeMethod(filePost);
try {
    BufferedReader rd = new BufferedReader(new InputStreamReader(
            filePost.getResponseBodyAsStream(), "UTF-8"));
    StringBuffer stringBuffer = new StringBuffer();
    String line;
    while ((line = rd.readLine()) != null) {
        stringBuffer .append(line);
    }
    rd.close();
    System.out.println("接受到的流是:" + stringBuffer + "—-" + status);
} catch (Exception e) {
    throw new RuntimeException("error”,e);

}

--------------------------------------------分割线----------------------------------------------------------

上面的代码模拟的表单为

===========================================================================================================================================

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
 
/**
  * Example how to use unbuffered chunk-encoded POST request.
  */
public class ClientChunkEncodedPost {
 
     public static void main(String[] args) throws Exception {
         if (args.length != 1 )  {
             System.out.println( "File path not given" );
             System.exit( 1 );
         }
         HttpClient httpclient = new DefaultHttpClient();
 
//        HttpPost httppost = new HttpPost("http://localhost:8088" +
//                "/client/test.jsp?username=用户&password=秘密");
//        HttpPost httppost = new HttpPost("http://localhost:8088/struts2/SendXmlServlet");
         HttpPost httppost = new HttpPost( "http://localhost:8088/struts2/StringServlet" );
         File file = new File(args[ 0 ]);
         InputStreamEntity reqEntity = new InputStreamEntity(
                 new FileInputStream(file), - 1 );
         reqEntity.setContentType( "binary/octet-stream" );
         reqEntity.setChunked( true );
         // It may be more appropriate to use FileEntity class in this particular
         // instance but we are using a more generic InputStreamEntity to demonstrate
         // the capability to stream out data from any arbitrary source
         //
         // FileEntity entity = new FileEntity(file, "binary/octet-stream");
         
         httppost.setEntity(reqEntity);
//         httppost.setEntity(entity);
         httpclient.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, 3000 ); //超时设置
         httpclient.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 3000 ); //连接超时
         System.out.println( "executing request " + httppost.getRequestLine());
         try {
             HttpResponse response = httpclient.execute(httppost);
             HttpEntity resEntity = response.getEntity();
     
             System.out.println( "----------------------------------------" );
             System.out.println(response.getStatusLine());
             if (resEntity != null ) {
                 System.out.println( "Response content length: " + resEntity.getContentLength());
                 System.out.println( "Chunked?: " + resEntity.isChunked());
                 InputStream is = resEntity.getContent();
                 BufferedReader reader = new BufferedReader(
                         new InputStreamReader(is));
                 try {
                     
                     // do something useful with the response
                     System.out.println(reader.readLine());
                     
                 } catch (IOException ex) {
     
                     // In case of an IOException the connection will be released
                     // back to the connection manager automatically
                     throw ex;
                     
                 } catch (RuntimeException ex) {
     
                     // In case of an unexpected exception you may want to abort
                     // the HTTP request in order to shut down the underlying
                     // connection and release it back to the connection manager.
                     httppost.abort();
                     throw ex;
                     
                 } finally {
     
                     // Closing the input stream will trigger connection release
                     reader.close();
                     
                 }
                 
             }
             if (resEntity != null ) {
                 resEntity.consumeContent();
             }
         } catch (IOException ex) {
             
             // In case of an IOException the connection will be released
             // back to the connection manager automatically
             throw ex;
             
         } catch (RuntimeException ex) {
             
             // In case of an unexpected exception you may want to abort
             // the HTTP request in order to shut down the underlying
             // connection and release it back to the connection manager.
             httppost.abort();
             throw ex;
             
         } finally {
 
             // Closing the input stream will trigger connection release
             
         }
         // When HttpClient instance is no longer needed,
         // shut down the connection manager to ensure
         // immediate deallocation of all system resources
         httpclient.getConnectionManager().shutdown();       
     }
     
}

=================================================================

StringServlet.java

====================================================================

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package com.test.servlet;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
 
 
public class StringServlet extends HttpServlet {
 
     /**
      * The doGet method of the servlet.
      *
      * This method is called when a form has its tag value method equals to get.
      *
      * @param request the request send by the client to the server
      * @param response the response send by the server to the client
      * @throws ServletException if an error occurred
      * @throws IOException if an error occurred
      */
     public void doGet(HttpServletRequest request, HttpServletResponse response)
             throws ServletException, IOException {
         doPost(request, response);
     }
 
     /**
      * The doPost method of the servlet.
      *
      * This method is called when a form has its tag value method equals to post.
      *
      * @param request the request send by the client to the server
      * @param response the response send by the server to the client
      * @throws ServletException if an error occurred
      * @throws IOException if an error occurred
      */
     public void doPost(HttpServletRequest request, HttpServletResponse response)
             throws ServletException, IOException {
         HttpClient client = new DefaultHttpClient();
         //InputStream is = new FileInputStream(new File("e:\\3.xml"));
         InputStream is = request.getInputStream();
         BufferedReader reader = new BufferedReader( new InputStreamReader(is));
         StringBuffer  result = new StringBuffer();
         String len;
         while ((len = reader.readLine()) != null ){
             result.append(len);
         }
         String xml = result.toString();
         System.out.println( "struts2.StringServlet:" + xml);
//        StringEntity reqEntity = new StringEntity(xml);
//        reqEntity.setContentType("application/x-www-form-urlencoded");
//       
         InputStreamEntity reqEntity = new InputStreamEntity(is,- 1 );
         reqEntity.setContentType( "binary/octet-stream" );
         reqEntity.setChunked( true );
         
         HttpPost post = new HttpPost( "http://localhost:8088/struts2/SendXmlServlet" );
         post.setEntity(reqEntity);
         HttpResponse res = client.execute(post);
         HttpEntity entity = res.getEntity();
         if (entity != null ){
             System.out.println( "Response content length: " + entity.getContentLength());
         }
         //显示结果
         BufferedReader resultReader = new BufferedReader( new InputStreamReader(entity.getContent()));
         String line = null ;
         while ((line = resultReader.readLine()) != null ){
             System.out.println(line);
         }
         if (entity != null ){
             entity.consumeContent();
         }
         
     }
 
}



你可能感兴趣的:(httpclient)