com.mingsoft.util.proxy.Proxy.java Source code

Java tutorial

Introduction

Here is the source code for com.mingsoft.util.proxy.Proxy.java

Source

/**
The MIT License (MIT) * Copyright (c) 2016 (mingsoft.net)
    
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
    
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
    
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

package com.mingsoft.util.proxy;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * ?get?post??
 * 
 * @author killfen
 * @version 1.0.0
 */
public class Proxy {

    // 
    public static Logger log = LoggerFactory.getLogger(Proxy.class);

    /**
     * get
     * 
     * @param url
     *            ?<br>
     * @param header
     *            ?Header new Header()<br>
     * @param params
     *            ?<br>
     * @return Result 
     */
    public static Result get(String url, com.mingsoft.util.proxy.Header header, Map params) {
        //log.info("?" + url);
        // Httpclient
        DefaultHttpClient client = new DefaultHttpClient();
        // ??
        url = url + (null == params ? "" : assemblyParameter(params));
        // get
        HttpGet httpGet = new HttpGet(url);
        // cookie?()
        httpGet.getParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);
        // ?
        if (null != header && header.getHeaders().size() > 0) {
            httpGet.setHeaders(Proxy.assemblyHeader(header.getHeaders()));
        }
        // ?HttpResponse
        HttpResponse response;
        try {
            response = client.execute(httpGet);
            // 
            // httpGet.abort();
            // HttpEntity
            HttpEntity entity = response.getEntity();
            // ??
            Result result = new Result();
            // cookie
            result.setCookie(assemblyCookie(client.getCookieStore().getCookies()));
            // ?
            result.setStatusCode(response.getStatusLine().getStatusCode());
            // 
            result.setHeaders(response.getAllHeaders());
            // ?
            result.setHttpEntity(entity);
            return result;
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return null;
    }

    /**
     * ?
     * 
     * @param url
     *            ?
     * @param path
     *            ???
     * @throws HttpException
     * @throws IOException
     */
    public static void get(String url, String path) {

        try {
            HttpClient hc = HttpClientBuilder.create().build();
            HttpGet gm = new HttpGet(url);
            HttpResponse response = hc.execute(gm);
            InputStream is = response.getEntity().getContent();
            OutputStream os = new FileOutputStream(path);
            int c = -1;
            while ((c = is.read()) != -1) {
                os.write(c);
            }
            is.close();
            os.flush();
            os.close();
        } catch (IOException e2) {
            e2.printStackTrace();
        }
    }

    /**
     * post
     * 
     * @param url
     *            ?<br>
     * @param header
     *            ?Header new Header()<br>
     * @param params
     *            ?<br>
     * @param encoding
     *            ??<br>
     * @return Result 
     */
    public static Result post(String url, com.mingsoft.util.proxy.Header header, Map params, String encoding) {
        //log.info("?" + url);
        // Httpclient
        DefaultHttpClient client = new DefaultHttpClient();
        // post
        HttpPost httpPost = new HttpPost(url);
        // cookie?()
        httpPost.getParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);
        // ????
        if (params != null) {
            List list = new ArrayList();

            Iterator it = params.keySet().iterator();
            while (it.hasNext()) {
                String temp = (String) it.next();
                list.add(new BasicNameValuePair(temp, params.get(temp) + ""));
            }

            try {
                httpPost.setEntity(new UrlEncodedFormEntity(list, encoding));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                log.error(e.getMessage());
            }
        }
        // 
        if (null != header && header.getHeaders().size() > 0) {
            httpPost.setHeaders(Proxy.assemblyHeader(header.getHeaders()));
        }
        // 
        HttpResponse response = null;
        try {
            response = client.execute(httpPost);
            HttpEntity entity = response.getEntity();
            // 
            // httpPost.abort();
            // ??
            Result result = new Result();
            // ??
            result.setStatusCode(response.getStatusLine().getStatusCode());
            // ?
            result.setHeaders(response.getAllHeaders());
            // cookie
            result.setCookie(assemblyCookie(client.getCookieStore().getCookies()));
            // ?
            result.setHttpEntity(entity);
            return result;
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return null;
    }

    /**
     * get??
     * 
     * @param url
     *            ?<br>
     * @param fileUrl
     *            ????<br>
     * @param header
     *            ?Header new Header()<br>
     */
    public static void getRandCode(String url, com.mingsoft.util.proxy.Header header, String fileUrl) {
        DefaultHttpClient client = new DefaultHttpClient();

        //log.info("?" + url);
        // get
        HttpGet get = new HttpGet(url);
        // cookie?()
        get.getParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);
        Map _headers = header.getHeaders();
        // ?
        if (null != header && _headers.size() > 0) {
            get.setHeaders(Proxy.assemblyHeader(_headers));
        }
        HttpResponse response;
        try {
            response = client.execute(get);

            // ?
            // Header[] h = (Header[]) response.getAllHeaders();
            // for (int i = 0; i < h.length; i++) {
            // Header a = h[i];
            // }

            HttpEntity entity = response.getEntity();
            InputStream in = entity.getContent();
            // cookie???cookie
            header.setCookie(assemblyCookie(client.getCookieStore().getCookies()));
            int temp = 0;
            // 
            File file = new File(fileUrl);
            // ??
            FileOutputStream out = new FileOutputStream(file);
            while ((temp = in.read()) != -1) {
                out.write(temp);
            }
            in.close();
            out.close();

        } catch (ClientProtocolException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
    }

    /**
     * ?
     * 
     * @param headers
     *            Header??<br>
     * @return Header
     */
    public static BasicHeader[] assemblyHeader(Map headers) {
        BasicHeader[] allHeader = new BasicHeader[headers.size()];
        int i = 0;
        //log.info("?");

        Iterator it = headers.keySet().iterator();
        while (it.hasNext()) {
            String str = (String) it.next();
            allHeader[i] = new BasicHeader(str, (String) headers.get(str));
            i++;
            //log.info(str + ":" + headers.get(str));
        }
        //log.info("??");
        return allHeader;
    }

    /**
     * cookie
     * 
     * @param cookies
     *            ?cookie <br>
     * @return cookie
     */
    public static String assemblyCookie(List cookies) {
        StringBuffer sbu = new StringBuffer();
        //log.info("cookie?");
        for (int i = 0; i < cookies.size(); i++) {
            Cookie cookie = (Cookie) cookies.get(i);
            sbu.append(cookie.getName()).append("=").append(cookie.getValue()).append(";");
            //log.info(cookie.getName() + ":" + cookie.getValue());
        }
        //log.info("?cookie?");
        if (sbu.length() > 0)
            sbu.deleteCharAt(sbu.length() - 1);
        return sbu.toString();
    }

    /**
     * ?
     * 
     * @param parameters
     *            ???<br>
     * @return ?
     */
    public static String assemblyParameter(Map parameters) {
        String para = "?";
        //log.info("?");
        Iterator it = parameters.keySet().iterator();
        while (it.hasNext()) {
            String str = (String) it.next();
            para += str + "=" + parameters.get(str) + "&";
            //log.info(str + ":" + parameters.get(str));
        }
        //log.info("??");
        return para.substring(0, para.length() - 1);
    }

}