httpUtil

//java学习交流QQ群    716298150
 

package com.common.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Map.Entry;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/*
 * 利用HttpClient进行post请求的工具类
 */
public class HttpClientUtil {
    static boolean proxySet = false;
    static String proxyHost = "127.0.0.1";
    static int proxyPort = 8080;

    /**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @param isproxy
     *            是否使用代理模式
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, HashMap<String, String> params, boolean isproxy) {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            HttpURLConnection conn = null;
            if (isproxy) {// 使用代理模式
                @SuppressWarnings("static-access")
                Proxy proxy = new Proxy(Proxy.Type.DIRECT.HTTP,
                        new InetSocketAddress(proxyHost, proxyPort));
                conn = (HttpURLConnection) realUrl.openConnection(proxy);
            } else {
                conn = (HttpURLConnection) realUrl.openConnection();
            }
            // 打开和URL之间的连接

            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST"); // POST方法

            // 设置通用的请求属性

            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");

            conn.connect();

            
             // 构建请求参数    
            StringBuffer sb = new StringBuffer();    
            if (params != null) {    
                for (Entry<String, String> e : params.entrySet()) {    
                    sb.append(e.getKey());    
                    sb.append("=");    
                    sb.append(e.getValue());    
                    sb.append("&");    
                }    
                sb=sb.deleteCharAt(sb.length() - 1);  
            }    
            
            // 获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            // 发送请求参数
            out.write(sb.toString());
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!" + e);
            e.printStackTrace();
            return "";
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }
    
    /**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @param isproxy
     *            是否使用代理模式
     * @return 所代表远程资源的响应结果
     */
    public static String sendPostJSON(String url, HashMap<String, String> params, boolean isproxy) {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            HttpURLConnection conn = null;
            if (isproxy) {// 使用代理模式
                @SuppressWarnings("static-access")
                Proxy proxy = new Proxy(Proxy.Type.DIRECT.HTTP,
                        new InetSocketAddress(proxyHost, proxyPort));
                conn = (HttpURLConnection) realUrl.openConnection(proxy);
            } else {
                conn = (HttpURLConnection) realUrl.openConnection();
            }
            // 打开和URL之间的连接

            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST"); // POST方法

            // 设置通用的请求属性

            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            conn.setRequestProperty("Content-Type","application/json");
            conn.connect();
            
             // 构建请求参数    
            StringBuffer sb = new StringBuffer();
            sb.append("{");
            if (params != null) {    
                Set<String> keySet = params.keySet();
                for (String key : keySet) {
                    sb.append("'"+key+"':'"+params.get(key)+"',");
                }
                sb.deleteCharAt(sb.length()-1);
                sb.append("}");
            }    
            
            // 获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            
            // 发送请求参数
            out.write(JSONObject.parseObject(sb.toString()).toString());
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader( conn.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!" + e);
            e.printStackTrace();
            return "";
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

/*    public String sendPost(String controller,String date)  {
        Properties props = new Properties();
        InputStream in;
        try {
            in = HttpClientUtil.class.getClassLoader().getResourceAsStream("db.properties");
            props.load(in);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
        String url =  props.getProperty("server_url") + controller;
        //String branch_id =  props.getProperty("branch_id");
        HashMap<String, String> parames = new HashMap<String, String>();    
        parames.put("author", "zhfxx");    
        parames.put("data", date);  
        String sr = sendPost(url, parames, false);
        return sr;
    }*/
    public static void main(String[] args) throws IOException {
        Properties props = new Properties();
        InputStream in;
        try {
            in = HttpClientUtil.class.getClassLoader().getResourceAsStream("resources/config.properties");
            props.load(in);
        }catch (Exception e) {
            
        }
        
        String url =  props.getProperty("loginver_url"); 
        HashMap<String, String> parames = new HashMap<String, String>();    
        parames.put("UserId", "146053");    
        parames.put("UserPwd", "qwer19880321+");  
        /*JSONObject user = new JSONObject(); 
        user.put("name", "赵云"); 
        user.put("age", "20");
        JSONObject user2 = new JSONObject(); 
        user2.put("name","马超"); 
        user2.put("age", "30");
        JSONArray userArray=new JSONArray();
        userArray.add(user);
        userArray.add(user2);
        parames.put("data", userArray.toJSONString());  */
        String sr = sendPost(url, parames, true);
        System.out.println(sr);
    }
    
    /*public static void main(String[] args) throws Exception{
        Properties props = new Properties();
        InputStream in;
        try {
            //in = new FileInputStream("./src/db.properties");
            //in = new FileInputStream("C:/db.properties");
            in = HttpClientUtil.class.getClassLoader().getResourceAsStream("db.properties");
            props.load(in);
        }catch (Exception e) {
            
        }
        String urlPath = props.getProperty("server_url") + "itme/uploadFlow"; 
        String param="author="+URLEncoder.encode("zhfxx","UTF-8");
        //建立连接
        URL url=new URL("http://10.85.132.11:8082/loginver/Handler.ashx?UserId=227512&UserPwd=QYJ@@@8888");
        System.out.println(url);
        HttpURLConnection httpConn=(HttpURLConnection)url.openConnection();
        //设置参数
        httpConn.setDoOutput(true); //需要输出
        httpConn.setDoInput(true); //需要输入
        httpConn.setUseCaches(false); //不允许缓存
        httpConn.setRequestMethod("POST"); //设置POST方式连接
        //设置请求属性
        httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        httpConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
        httpConn.setRequestProperty("Charset", "UTF-8");
        //连接,也可以不用明文connect,使用下面的httpConn.getOutputStream()会自动connect
        httpConn.connect();
        //建立输入流,向指向的URL传入参数
        DataOutputStream dos=new DataOutputStream(httpConn.getOutputStream());
        dos.writeBytes(param);
        dos.flush();
        dos.close();
        //获得响应状态
        int resultCode=httpConn.getResponseCode();
        if(HttpURLConnection.HTTP_OK==resultCode){
        StringBuffer sb=new StringBuffer();
        String readLine=new String();
        BufferedReader responseReader=new BufferedReader(new InputStreamReader(httpConn.getInputStream(),"UTF-8"));
        while((readLine=responseReader.readLine())!=null){
            sb.append(readLine).append("\n");
        }
        responseReader.close();
        System.out.println(sb.toString());
        } 
    }*/
    
    //jiabo50以后
     public static String sendPostProXy(String url, String param, Map<String, String> header) throws UnsupportedEncodingException, IOException {
            PrintWriter out = null;
            BufferedReader in = null;
            String result = "";
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            //设置超时时间
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(15000);
            
            //jiabo50以后
            conn.setRequestProperty( "proxyPort", "8888");
            
            // 设置通用的请求属性
            if (header!=null) {
                for (Entry<String, String> entry : header.entrySet()) {
                    conn.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            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(), "utf8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            if(out!=null){
                out.close();
            }
            if(in!=null){
                in.close();
            }
            return result;
        }

    
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值