httpclient4学习模拟通过流的形式向Servlet发送请求及超时的控制

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

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

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. <br>
     *
     * 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. <br>
     *
     * 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();
        }
        
    }

}
原文地址:https://www.cnblogs.com/chinareny2k/p/1691624.html