Java实现发送Get和Post请求

来源:互联网 发布:VPN服务器端软件 编辑:程序博客网 时间:2024/05/19 06:18

前言

已经有几天没有写博客了 , 原因是最近生活中有大量的事情, 尽管每天都在学习 , 但是却没有将知识点记录在博客中 , 感觉这样非常不好 .

  • 以后一定要坚持写博客 , 记录自己成长历程
  • 希望可以在这里找到一些志同道合的朋友 , 一起努力 , 一起进步.

总结归类

  1. Java创建代理连接对象
  2. Java发送Post请求
  3. Java发送Get请求

代码

Java创建代理连接对象

    /**     * 1.返回代理对象     * @param proxyIp     * @param proxyPort     * @return     */    public Proxy setProxy(String proxyIp , int proxyPort ){        try{            InetSocketAddress socketAddress                 = new InetSocketAddress(proxyIp , proxyPort );            Proxy proxy = new Proxy(Proxy.Type.HTTP , socketAddress );            return proxy;        }catch(Exception e ){            e.printStackTrace();        }        return null;    }

Java发送Get请求

    /**     * 2.发送Get请求     * @param url        * @param params             * 表示链接后面的一些参数 如name=ghoset&pass=ghoset     * @return     */    public String sendGet(String url , String params ) throws Exception {        StringBuilder builder = new StringBuilder();        if(params != null || params.length() != 0  ){            url = url + "?" + params;   //重新构造URL链接         }        URL Url  = new URL(url );        URLConnection conn =  Url.openConnection();        // 设置代理        //URLConnection conn = Url.openConnection(setProxy(proxyHost, proxyPort));        // 如果需要设置代理账号密码则添加下面一行        //conn.setRequestProperty("Proxy-Authorization", "Basic "+Base64.encode("account:password".getBytes()));        //发送数据包(可以直接抓取浏览器数据包然后复制)        conn.setRequestProperty("accept", "*/*" );        conn.setRequestProperty("Connection", "Keep-Alive" );        conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36");        conn.connect();        //接收响应的数据包        Map<String , List<String > > map = conn.getHeaderFields();        Set<String > set = map.keySet();        for(String k : set ){            String v = conn.getHeaderField(k );            System.out.println(k + ":" + v  );        }        //返回浏览器的输出信息        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream() ));        String line = reader.readLine();        line = new String(line.getBytes() , "gbk" );        //实现将字符串转成gbk类型显示.        while(line != null ){            builder.append(line +"\r\n" );            System.out.println(line );            line = reader.readLine();        }        //释放资源        reader.close();        return builder.toString();    }

Java发送Post请求

/**     * 3.发送POST请求     * @param url     * @param params     * @param forData     * @return     * @throws Exception     */    public String sendPost(String url , String params  , String formData) throws Exception{        StringBuilder builder = new StringBuilder();        if(!(params == null || params.length() == 0) ){            url += ("?" + params );         }        URL Url = new URL(url );        URLConnection conn = Url.openConnection();        //如果设置代理 , 和发送GET一样.        conn.setRequestProperty("accept", "*/*" );        conn.setRequestProperty("Connection", "Keep-Alive" );        conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36");        //设置之后就可以发送POST请求了        conn.setDoInput(true );        conn.setDoOutput(true );        //获取它的输出流 , 直接写入post请求        PrintWriter writer = new PrintWriter(conn.getOutputStream() );        writer.print(formData );                                            writer.flush();        //获取浏览器的返回数据        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream() ) );        String line = reader.readLine();        line = new String(line.getBytes() , "utf-8" );  //解决乱码的问题        while(line != null ){            System.out.println(line );            builder.append(line + "\r\n" );            line = reader.readLine();        }        reader.close();        writer.close();        return builder.toString();    }

测试方法

    public static void main(String[] args) {        HttpRequestUtil request = new HttpRequestUtil();        try{            Proxy proxy = request.setProxy(InetAddress.getLocalHost().getHostAddress() , 8888 );        System.out.println(proxy );    //Get请求                 request.sendGet("http://localhost/review/html/index.php", "username=ghoset&password=ghoset" );    //Post请求                String formData = "username=ghoset&password=ghoset";            String rs = request.sendPost("http://localhost/review/java/index.php", null , formData );        }catch(Exception e ){            e.printStackTrace();        }
原创粉丝点击