java - 模拟HttpPost请求发送后,对面重定向了,如何获取其URL?
ringa_lee
ringa_lee 2017-04-18 10:23:17
[Java讨论组]

模拟Post请求的代码

/**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            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()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }    

测试代码

    @Test
    public void TestHttpRequestPost() {
        String result = MockHttpRequest.sendPost("http://pastebin.ubuntu.com/",
                "poster=中文测试&syntax=text&content=TestContext");
        System.out.println(result);
        assertNotNull(result);
    }

返回的内容是网页源代码,其中有<a class="pturl" href="/23527018/plain/">Download as text</a>,那么"http://pastebin.ubuntu.com/"拼接上"23527018/"以后就是我想要的了。不过还要写正则表达去提取,感觉不是很优雅

  • 请问各位有什么好的方法吗?

  • 第二个问题:如何在这种情况下获取Response头呢?

ringa_lee
ringa_lee

ringa_lee

全部回复(2)
PHPz

当参数值的形式传递给你啊

大家讲道理

jsoup 试试?

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号