java Http原生 Get 和Post 支持代理认证

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;

public class HttpUtil {
    /**
     * 
     * @param urlString 请求url
     * @param res 返回结果
     * @param timeOut 超时时间(min)
     * @param useProxy 是否使用代理
     * @return
     * @throws Exception
     */
    public static  String sendGet(String urlString, String res, String timeOut, boolean useProxy) throws Exception {
        URL url = new URL(urlString);
        URLConnection uc = null;
        //判断是否用代理
        if(useProxy){
            //使用代理
            InetSocketAddress isa = new InetSocketAddress(PropertiesUtil.properties.getProperty("proxy_host"), Integer.parseInt(PropertiesUtil.properties.getProperty("proxy_port")));
            Proxy proxy = new Proxy(Proxy.Type.HTTP, isa);
            Authenticator.setDefault(new MyAuthenticator(PropertiesUtil.properties.getProperty("proxy_user"), PropertiesUtil.properties.getProperty("proxy_password")));
            uc = url.openConnection(proxy);
        }else{
            //不用代理
            uc = url.openConnection();
        }
        uc.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
        uc.setReadTimeout(60 * 1000 * Integer.parseInt(timeOut));
        uc.setDoOutput(true);
        uc.setDoInput(true);
        InputStream is = uc.getInputStream();
        int c;
        StringBuffer sf = new StringBuffer();
        while ((c = is.read()) != -1) {
            sf.append((char) c);
        }
        byte[] b2 = sf.toString().getBytes("ISO8859_1");
        String ss = new String(b2, "UTF-8");
        res = ss;
        is.close();
        return res;
    }
    
     public static String sendPost(String urlString, String param, String res, String timeOut, boolean useProxy) throws Exception {
        PrintWriter out = null;
        BufferedReader in = null;
        URLConnection conn = null;
        String result = "";
        URL realUrl = new URL(urlString);
        //判断是否用代理
          if(useProxy){
              //使用代理
              InetSocketAddress isa = new InetSocketAddress(PropertiesUtil.properties.getProperty("proxy_host"), Integer.parseInt(PropertiesUtil.properties.getProperty("proxy_port")));
              Proxy proxy = new Proxy(Proxy.Type.HTTP, isa);
              Authenticator.setDefault(new MyAuthenticator(PropertiesUtil.properties.getProperty("proxy_user"), PropertiesUtil.properties.getProperty("proxy_password")));
              conn = realUrl.openConnection(proxy);
          }else{
              // 打开和URL之间的连接
              conn = realUrl.openConnection();
          }
        // 设置通用的请求属性
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
        conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        // 发送POST请求必须设置如下两行
        conn.setDoOutput(true);
        conn.setDoInput(true);
        // 获取URLConnection对象对应的输出流
        out = new PrintWriter(conn.getOutputStream());
        // 发送请求参数
        out.print(param);
        // flush输出流的缓冲
        out.flush();
        // 定义BufferedReader输入流来读取URL的响应
        in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
        //使用finally块来关闭输出流、输入流
        if(out!=null){
            out.close();
        }
        if(in!=null){
            in.close();
        }
        return result;
    } 
    
    public static class MyAuthenticator extends Authenticator {
        private String user = "";
        private String password = "";

        public MyAuthenticator(String user, String password) {
            this.user = user;
            this.password = password;
        }

        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(user, password.toCharArray());
        }
    }

    public static void main(String[] args) throws Exception {
//        System.out.println(HttpUtil.sendGet("http://www.baidu.com", "", "5", true));
        System.out.println(HttpUtil.sendPost("http://www.baidu.com","","", "5", true));
    }
}

 

posted @ 2016-08-10 17:06  Earic  阅读(419)  评论(0编辑  收藏  举报