클 라 이언 트 HttpClient 처리 Servlet Gzip

10740 단어 httpclient
서버 는 gzip 을 사용 하여 텍스트 내용 을 압축 처리 하고 클 라 이언 트 는 HttpClient 를 사용 하여 데 이 터 를 가 져 오고 gzip 압축 을 풀 수 있 습 니 다.
서버
public class GzipTestServlet extends HttpServlet {



    protected void processRequest(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        response.setHeader("Cache-Control", "no-cache");

        response.setContentType("text/html;charset=UTF-8");

        

        String str = "    this is a test!";

        

        if (isGzipSupport(request)) {//  gzip

            response.setHeader("Content-Encoding", "gzip");

            OutputStream os = response.getOutputStream();

            GZIPOutputStream gs = new GZIPOutputStream(os);

            gs.write(str.getBytes("UTF-8"));//        

            gs.finish();

            gs.close();

            os.close();

        } else {

            PrintWriter out = response.getWriter();

            out.write(str);

            out.flush();

            out.close();

        }

    }



    /**

     *            gzip    

     * @param request

     * @return

     */

    private boolean isGzipSupport(HttpServletRequest request) {

        String headEncoding = request.getHeader("accept-encoding");

        return (headEncoding != null && (headEncoding.indexOf("gzip") != -1));

    }



    @Override

    protected void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        processRequest(request, response);

    }



    @Override

    protected void doPost(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        processRequest(request, response);

    }

}

클 라 이언 트
Http Client 3.1 을 사용 합 니 다.
(1)UngzipPostMethod.java
/**

 *   PostMethod  getResponseBodyAsString    Gzip   */

public class UngzipPostMethod extends org.apache.commons.httpclient.methods.PostMethod{

    public UngzipPostMethod(String uri){

        super(uri);

    }



    @Override

    public String getResponseBodyAsString() throws IOException {

        GZIPInputStream gzin;

        if(getResponseBody()!=null ||getResponseStream() != null ){

            if(getResponseHeader("Content-Encoding") != null && getResponseHeader("Content-Encoding").getValue().toLowerCase().indexOf("gzip") != -1) {  

                InputStream is = getResponseBodyAsStream();

                gzin = new GZIPInputStream(is);

                

                InputStreamReader isr = new InputStreamReader(gzin,getResponseCharSet());

                

                BufferedReader br = new BufferedReader(isr);

                StringBuilder sb = new StringBuilder();

                String tmp;

                while((tmp = br.readLine())!=null){

                    sb.append(tmp);

                    sb.append("\r
"); } br.close(); isr.close(); return sb.toString(); }else{ // return super.getResponseBodyAsString(); } }else{ return null; } } }

(2)HttpUtil.java
public class HttpUtil {

    /**

     *          

     * @param url

     * @param list

     * @return 

     */

    public String postGzipRequest(String url, List<NameValuePair> list){

        HttpClient client = new HttpClient();

        UngzipPostMethod post = new UngzipPostMethod(url);

        post.setRequestHeader("Accept-Encoding", "gzip, deflate");

        post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");  

        StringBuilder sb = new StringBuilder();

        

        if(list!=null){

            int len = list.size();

            NameValuePair[] params = new NameValuePair[len];

            for(int i=0; i<len; i++){

                params[i] = list.get(i);

            }

            post.setRequestBody(params);

        }

        try {

            //  post

            int statusCode = client.executeMethod(post);

            

            if (statusCode == HttpStatus.SC_OK) {

                 sb.append(post.getResponseBodyAsString());

            }

            

        } catch (IOException ex) {

            java.util.logging.Logger.getLogger(HttpUtil.class.getName()).log(Level.SEVERE, null, ex);

        }

        return sb.toString();

    }
}

(3)Test.java
public class Test {

    public static void main(String args[]){

       HttpUtil httpUtil = new HttpUtil();

       String url = "http://localhost:8080/tsmanager/GzipTestServlet.do";

       System.out.println("  :"+httpUtil.postGzipRequest(url, null));

    }

}

 

좋은 웹페이지 즐겨찾기