求java模拟登陆例子,谢谢,能用的,

wugang789 发布于 2013/08/08 14:04
阅读 557
收藏 0
加载中
0
南湖船老大
南湖船老大

主要是 HttpURLConnection 类的应用,我在他上面封装了一小下 。

主要代码

private String getContent(String method, String charset,boolean out) throws IOException {
    	HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod(method);
            conn.setReadTimeout(timeout);
            if (headers != null) {
                for (Entry<String, String> entry : headers.getHeaders().entrySet()) {
                    conn.addRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            if (METHOD_POST.equals(method) && queryString != null) {
                conn.setDoOutput(true);
                conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
                conn.getOutputStream().write(queryString.getBytes());
            }           
            conn.connect();            
            InputStream is1 = conn.getInputStream();
            if(METHOD_POST.equals(method) &&out==false) return "SUCCESS";
			InputStream is2 = null;
            String encoding = conn.getContentEncoding();
            // 如果采用了压缩,则需要处理否则都是乱码
			if (encoding != null && encoding.contains("gzip")) {
				is2 = new GZIPInputStream(is1);
			} else if (encoding != null && encoding.contains("deflate")) {
				is2 = new InflaterInputStream(is1);
			} else {
				is2 = is1;
			}
            return TextFileHelper.read(is2, charset);
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    }

    public String doGet() {
        try {
			return getContent(METHOD_GET, charset,true);
		} catch (IOException e) {
			e.printStackTrace();
			return "";
		}
    }

    public String doPost(boolean showReturnData) {
        try {
			return getContent(METHOD_POST, charset,showReturnData);
		} catch (IOException e) {
			e.printStackTrace();
			return "ERROR";		
		}
    }
应用:
HTTPClient curl=new HTTPClient("http://test.com/post.php");
//		System.out.println(curl.doGet());
		RequestHeaders headers =curl.getHeaders();
		headers.setReferer("http://test.com/archives/1/");
		headers.setHost("test.com");
		headers.setHeader("Cookie", "PHPSESSID=e1724452dbcf2fac7e1102140d0c0fb4");
//		System.out.println(headers.getHeaders().get("Content-Length"));
//		Map<String, String> params = new HashMap<String, String>();
//        params.put("author", "测试");
//        params.put("mail", "itest@125.com");
//        params.put("text", "test22");
		curl.setQueryString("author=%E6%B5%8B%E8%AF%95&mail=itest@125.com&url=&text=%E5%BE%88%E5%A5%BD");
		System.out.println(curl.doPost(false));
0
徐迎龙
徐迎龙
遇到验证码,就没办法了,除非能解析验证码图片
wugang789
wugang789
就是啊【登录失败】【错误代码:需要输入验证码】【账号:634143248】正在尝试重新登录.... 【登录失败】【错误代码:需要输入验证码】【账号:634143248】正在尝试重新登录.... 【登录失败】【错误代码:需要输入验证码】【账号:634143248】正在尝试重新登录....
返回顶部
顶部