文档章节

java httpclient 为邮箱添加来信转发规则

Hysteria_
 Hysteria_
发布于 2014/06/06 15:30
字数 1817
阅读 367
收藏 8
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
 
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

/**
 * 对网易yeah.net邮箱用户添加转发规则
 * 
 * @since 2014-6-6 14:52:09
 */
public class MailYeahTest {
    public static final String SESSION_INIT = "http://mail.yeah.net";
    public static final String LOGIN_URL = "https://mail.yeah.net/entry/cgi/ntesdoor?df=webmailyeah&from=web&funcid=loginone&iframe=1&language=-1&passtype=1&verifycookie=1&product=mailyeah&style=-1&uid=";
    public static final String RULE_POST_URl = "http://mail.yeah.net/js5/s?sid={0}&func=user:addMailRules";
    public static final String RULE_LIST_URl = "http://mail.yeah.net/js5/s?sid={0}&func=user:getMailRules&from=nav&group=options-0&id=NaN&action=click";
    public static final String RULE_NAME = "规则名称";
    public static final String FORWARD_MAIL = "你要转到的email地址";
    /**
     * @param args
     */
    public static void main(String[] args) {
        HttpClientHelper hc = new HttpClientHelper(true);
        HttpResult lr = hc.get(SESSION_INIT);// 目的是得到 csrfToken 类似
        
        // 拼装登录信息
        Map<String, String> data = new HashMap<String, String>();
        String username ;
        data.put("username", username ="*******@yeah.net");
        data.put("savelogin", "0");
        data.put("url2", "http://mail.yeah.net/errorpage/err_yeah.htm");
        data.put("password", "********");
        lr = hc.post(LOGIN_URL, data,setHeader());// 执行登录
        Document doc = Jsoup.parse(lr.getHtml());
        System.out.println("doc========"+doc);
        String sessionId=doc.select("script").html().split("=")[2];
        sessionId = sessionId.substring(0,sessionId.length()-2);
        System.out.println("sessionId=========="+sessionId);
        
        //查询用户的来来信列表中是否包含“***”字样	 有则不再进行转发规则的添加
        data.clear();
        data.put("var", "<?xml version=\"1.0\"?><object/>");
        lr = hc.post(MessageFormat.format(RULE_LIST_URl, sessionId),data, setHeaderTORuleList(sessionId));
        
        //转发
        if(!lr.getHtml().contains(RULE_NAME)){
	        data.clear();               
	        data.put("var", "<?xml version=\"1.0\"?><object><array name=\"items\"><object><string name=\"name\">"+RULE_NAME+"</string><boolean name=\"disabled\">false</boolean><boolean name=\"continue\">true</boolean><array name=\"condictions\"><object><boolean name=\"disabled\">false</boolean><string name=\"field\">subject</string><string name=\"operand\">我是好人</string><boolean name=\"ignoreCase\">true</boolean><string name=\"operator\">contains</string></object><object><string name=\"field\">accounts</string><string name=\"operator\">contains</string><array name=\"operand\"><string>"+username+"</string></array></object></array><array name=\"actions\"><object><string name=\"type\">forward</string><string name=\"target\">"+FORWARD_MAIL+"</string><boolean name=\"keepLocal\">true</boolean></object></array></object></array></object>");
	        lr = hc.post(MessageFormat.format(RULE_POST_URl, sessionId),data, setHeaderTORulePost(sessionId));
	        
	        data.clear();
	        data.put("var", "<?xml version=\"1.0\"?><object><array name=\"items\"><object><string name=\"name\">"+RULE_NAME+"</string><boolean name=\"disabled\">false</boolean><boolean name=\"continue\">true</boolean><array name=\"condictions\"><object><boolean name=\"disabled\">false</boolean><string name=\"field\">subject</string><string name=\"operand\">你是坏人</string><boolean name=\"ignoreCase\">true</boolean><string name=\"operator\">contains</string></object><object><string name=\"field\">accounts</string><string name=\"operator\">contains</string><array name=\"operand\"><string>"+username+"</string></array></object></array><array name=\"actions\"><object><string name=\"type\">forward</string><string name=\"target\">"+FORWARD_MAIL+"</string><boolean name=\"keepLocal\">true</boolean></object></array></object></array></object>");
	        lr = hc.post(MessageFormat.format(RULE_POST_URl, sessionId),data, setHeaderTORulePost(sessionId));
	        
	        data.clear();
	        data.put("var", "<?xml version=\"1.0\"?><object><array name=\"items\"><object><string name=\"name\">"+RULE_NAME+"</string><boolean name=\"disabled\">false</boolean><boolean name=\"continue\">true</boolean><array name=\"condictions\"><object><boolean name=\"disabled\">false</boolean><string name=\"field\">subject</string><string name=\"operand\">呵呵</string><boolean name=\"ignoreCase\">true</boolean><string name=\"operator\">contains</string></object><object><string name=\"field\">accounts</string><string name=\"operator\">contains</string><array name=\"operand\"><string>"+username+"</string></array></object></array><array name=\"actions\"><object><string name=\"type\">forward</string><string name=\"target\">"+FORWARD_MAIL+"</string><boolean name=\"keepLocal\">true</boolean></object></array></object></array></object>");
	        lr = hc.post(MessageFormat.format(RULE_POST_URl, sessionId),data, setHeaderTORulePost(sessionId));
        }
        System.out.println(lr.getHtml());	//响应信息
    }
     
    public static Header[] setHeader() {
        Header[] result = {
        		new BasicHeader("User-Agent","Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"),
                new BasicHeader("Accept-Encoding","gzip, deflate"),
                new BasicHeader("Accept-Language","zh-CN"),
                new BasicHeader("Connection","Keep-Alive"),
                new BasicHeader("Host","mail.yeah.net"),
                new BasicHeader("Referer","http://mail.yeah.net/"),
                new BasicHeader("Accept","text/html, application/xhtml+xml, */*")
                 
        };
        return result;
    }
    public static Header[] setHeaderTORulePost(String sessionId) {
        Header[] result = {
        		new BasicHeader("Host","mail.yeah.net"),
                new BasicHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0"),
                new BasicHeader("Accept","text/javascript"),
                new BasicHeader("Accept-Language","zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3"),
                new BasicHeader("Accept-Encoding","gzip, deflate"),
                new BasicHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8"),
                new BasicHeader("Referer","http://mail.yeah.net/js5/main.jsp?sid="+sessionId+"&df=webmailyeah"),
                new BasicHeader("Connection","Keep-Alive"),
        		new BasicHeader("Pragma","no-cache"),
        		new BasicHeader("Cache-Control","no-cache")
                 
        };
        return result;
    }
    public static Header[] setHeaderTORuleList(String sessionId) {
        Header[] result = {
        		new BasicHeader("Host","mail.yeah.net"), 
                new BasicHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0"),
                new BasicHeader("Accept","text/javascript"),
                new BasicHeader("Accept-Language","zh-CN"),
                new BasicHeader("Accept-Encoding","gzip, deflate"),
                new BasicHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8"),
                new BasicHeader("Referer","http://mail.yeah.net/js5/main.jsp?sid="+sessionId+"&df=webmailyeah"),
                new BasicHeader("Connection","Keep-Alive"),
                new BasicHeader("Pragma","no-cache"),
                new BasicHeader("Cache-Control","no-cache")
                 
        };
        return result;
    }
}


-----------------------------------------------------------------------------------------------
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
 
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
 
import org.apache.commons.lang.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
/**
 * HttpClient 封装
 *
 * @author bangis.wangdf
 */
public class HttpClientHelper {
 
    private HttpClient       httpclient       = new DefaultHttpClient();
    private HttpContext      localContext     = new BasicHttpContext();
    private BasicCookieStore basicCookieStore = new BasicCookieStore();                          // cookie存储用来完成登录后记录相关信息
 
    private int              TIME_OUT         = 3;                                              // 连接超时时间
 
    public HttpClientHelper() {
        instance();
    }
 
    /**
     * 启用cookie存储
     */
    private void instance() {
        httpclient.getParams().setIntParameter("http.socket.timeout", TIME_OUT * 1000);
        localContext.setAttribute("http.cookie-store", basicCookieStore);// Cookie存储
    }
 
    /**
     * @param ssl boolean=true 支持https网址,false同默认构造
     */
    public HttpClientHelper(boolean ssl) {
        instance();
        if (ssl) {
            try {
                X509TrustManager tm = new X509TrustManager() {
 
                    public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
                    }
 
                    public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
                    }
 
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                };
                SSLContext ctx = SSLContext.getInstance("TLS");
                ctx.init(null, new TrustManager[] { tm }, null);
                SSLSocketFactory ssf = new SSLSocketFactory(ctx);
                ClientConnectionManager ccm = httpclient.getConnectionManager();
                SchemeRegistry sr = ccm.getSchemeRegistry();
                sr.register(new Scheme("https", ssf, 443));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
 
    /**
     * @param url
     * @param headers 指定headers
     * @return
     */
    public HttpResult get(String url, Header... headers) {
        HttpResponse response;
        HttpGet httpget = new HttpGet(url);
        if (headers != null) {
            for (Header h : headers) {
                httpget.addHeader(h);
            }
        } else {// 如不指定则使用默认
            Header header = new BasicHeader(
                                            "User-Agent",
                                            "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1;  .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; InfoPath.2)");
            httpget.addHeader(header);
        }
        HttpResult httpResult = HttpResult.empty();
        try {
            response = httpclient.execute(httpget, localContext);
            httpResult = new HttpResult(localContext, response);
        } catch (IOException e) {
            httpget.abort();
        }
        return httpResult;
    }
 
    public HttpResult post(String url, Map<String, String> data, Header... headers) {
        HttpResponse response;
        HttpPost httppost = new HttpPost(url);
        String contentType = null;
        if (headers != null) {
            int size = headers.length;
            for (int i = 0; i < size; ++i) {
                Header h = (Header) headers[i];
                if (!(h.getName().startsWith("$x-param"))) {
                    httppost.addHeader(h);
                }
                if ("Content-Type".equalsIgnoreCase(h.getName())) {
                    contentType = h.getValue();
                }
            }
 
        }
        if (contentType != null) {
            httppost.setHeader("Content-Type", contentType);
        } else if (data != null) {
            httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        }
 
        List<NameValuePair> formParams = new ArrayList<NameValuePair>();
        for (String key : data.keySet()) {
            formParams.add(new BasicNameValuePair(key, (String) data.get(key)));
        }
        HttpResult httpResult = HttpResult.empty();
        try {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, "UTF-8");
            httppost.setEntity(entity);
            response = httpclient.execute(httppost, localContext);
            httpResult = new HttpResult(localContext, response);
        } catch (IOException e) {
            httppost.abort();
        } finally {
        }
        return httpResult;
    }
 
    public String getCookie(String name, String... domain) {
        String dm = "";
        if (domain != null && domain.length >= 1) {
            dm = domain[0];
        }
        for (Cookie c : basicCookieStore.getCookies()) {
            if (StringUtils.equals(name, c.getName()) && StringUtils.equals(dm, c.getDomain())) {
                return c.getValue();
            }
        }
        return null;
    }
 
    public void pringCookieAll() {
        for (Cookie c : basicCookieStore.getCookies()) {
            System.out.println(c);
        }
    }
}




-----------------------------------------------------------------------------------------------
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
 
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
 
import org.apache.commons.lang.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
/**
 * 对HttpClient返回的结果进一步封装
 * @author bangis.wangdf
 *
 */
public class HttpResult {
     
     
    private static Pattern headerCharsetPattern = Pattern.compile(
            "charset=((gb2312)|(gbk)|(utf-8))", 2);
    private static Pattern pattern = Pattern
            .compile(
                    "<meta[^>]*content=(['\"])?[^>]*charset=((gb2312)|(gbk)|(utf-8))\\1[^>]*>",
                    2);
    private String headerCharset;
    private String headerContentType;
    private String headerContentEncoding;
    private List<Header> headers;
    private String metaCharset;
    private byte[] response;
    private String responseUrl;
    private int statuCode = -1;
    private static final int BUFFER_SIZE = 4096;
 
    public static HttpResult empty() {
        return new HttpResult();
    }
 
    public String getHeaderCharset() {
        return this.headerCharset;
    }
 
    public String getHeaderContentType() {
        return this.headerContentType;
    }
 
    public final List<Header> getHeaders() {
        return this.headers;
    }
 
    public String getHtml() {
        try {
            return getText();
        } catch (UnsupportedEncodingException e) {
        }
        return "";
    }
     
    public String getHtml(String encoding) {
        try {
            return getText(encoding);
        } catch (UnsupportedEncodingException e) {
        	e.printStackTrace();
        }
        return "";
    }
 
    public String getMetaCharset() {
        return this.metaCharset;
    }
 
    public byte[] getResponse() {
        return Arrays.copyOf(this.response, this.response.length);
    }
 
    public String getResponseUrl() {
        return this.responseUrl;
    }
 
    public int getStatuCode() {
        return this.statuCode;
    }
 
    public String getText() throws UnsupportedEncodingException {
        return getText("");
    }
 
    public String getText(String encoding) throws UnsupportedEncodingException {
        if (this.response == null){
            return "";
        }
        String encodingStr = encoding;
        if (StringUtils.isBlank(encoding)){
            encodingStr = this.metaCharset;
        }
 
        if (StringUtils.isBlank(encoding)){
            encodingStr = this.headerCharset;
        }
 
        if (StringUtils.isBlank(encoding)){
            encodingStr = "UTF-8";
        }
 
        return new String(this.response, encodingStr);
    }
 
    private String getCharsetFromMeta() {
        StringBuilder builder = new StringBuilder();
        String charset = "";
        for (int i = 0; (i < this.response.length) && ("".equals(charset)); ++i) {
            char c = (char) this.response[i];
            switch (c) {
            case '<':
                builder.delete(0, builder.length());
                builder.append(c);
                break;
            case '>':
                if (builder.length() > 0){
                    builder.append(c);
                }
                String meta = builder.toString();
 
                if (meta.toLowerCase().startsWith("<meta")){
                    charset = getCharsetFromMeta(meta);
                }
                break;
            case '=':
            default:
                if (builder.length() > 0){
                    builder.append(c);
                }
            }
 
        }
 
        return charset;
    }
 
    private String getCharsetFromMeta(String meta) {
        if (StringUtils.isBlank(meta)){
            return "";
        }
        Matcher m = pattern.matcher(meta);
        if (m.find()){
            return m.group(2);
        }
        return "";
    }
 
    private void getHttpHeaders(HttpResponse httpResponse) {
        String headerName = "";
        String headerValue = "";
        int index = -1;
 
        Header[] rspHeaders = httpResponse.getAllHeaders();
        for (int i = 0; i < rspHeaders.length; ++i) {
            Header header = rspHeaders[i];
            this.headers.add(header);
 
            headerName = header.getName();
            if ("Content-Type".equalsIgnoreCase(headerName)) {
                headerValue = header.getValue();
                index = headerValue.indexOf(';');
                if (index > 0){
                    this.headerContentType = headerValue.substring(0, index);
                }
                Matcher m = headerCharsetPattern.matcher(headerValue);
                if (m.find()){
                    this.headerCharset = m.group(1);
                }
            }
 
            if ("Content-Encoding".equalsIgnoreCase(headerName)){
                this.headerContentEncoding = header.getValue();
            }
        }
    }
 
    private void getResponseUrl(HttpContext httpContext) {
        HttpHost target = (HttpHost) httpContext
                .getAttribute("http.target_host");
 
        HttpUriRequest req = (HttpUriRequest) httpContext
                .getAttribute("http.request");
 
        this.responseUrl = target.toString() + req.getURI().toString();
    }
 
    public HttpResult(HttpContext httpContext, HttpResponse httpResponse) {
        this.headers = new ArrayList<Header>();
 
        this.statuCode = httpResponse.getStatusLine().getStatusCode();
 
        if (httpContext != null) {
            getResponseUrl(httpContext);
        }
 
        if (httpResponse != null) {
            getHttpHeaders(httpResponse);
            try {
                if (("gzip".equalsIgnoreCase(this.headerContentEncoding))
                        || ("deflate".equalsIgnoreCase(this.headerContentEncoding))) {
                    GZIPInputStream is = new GZIPInputStream(httpResponse.getEntity().getContent());
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    byte[] buffer = new byte[BUFFER_SIZE];
                    int count = 0;
                    while ((count = is.read(buffer)) > 0){
                        os.write(buffer, 0, count);
                    }
                    this.response = os.toByteArray();
                    os.close();
                    is.close();
                }else{
                    this.response = EntityUtils.toByteArray(httpResponse.getEntity());
                }
            } catch (Exception e) {
            	e.printStackTrace();
            }
            if (this.response != null){
                this.metaCharset = getCharsetFromMeta();
            }
        }
    }
 
    private HttpResult() {
    }
}


© 著作权归作者所有

共有 人打赏支持
Hysteria_
粉丝 0
博文 2
码字总数 1886
作品 0
海淀
程序员
Android 使用自带的HttpClient进行https请求出现403的解决过程记录

出现的过程 最近在用程序模拟一个web站的https登录,然后进行一些后续操作的小玩意。先使用java程序写测试代码,测试通过移植到android。 java基于httpclient-4.3.1.jar开发。 android端使用...

atearsan
2014/03/05
0
1
httpclient4.4 出现NoHttpResponseException的异常解决

httpclient4.4简单初始化httpclient的方式: 使用连接池初始化httpclient的方式: 但在测试过程中发现,有时候出现如下的异常,但重试一次就没有问题: 网上查了相关的报错信息,找到官网上的...

一路向北的兔斯基
2015/07/30
0
1
使用jetty 自带的http client!

一般情况下我们需要使用HttpClient时可供选择的技术有: 1、HttpURLConnection 2、Apache HttpClient 其他的除了写Socket 我都没有用过了。 偶然的机会发现Jetty 里面也自带了一个HttpClien...

一堆BUG
2012/02/27
0
0
Android 浅谈HttpClient工具类

在Android开发中我们经常会用到网络连接功能与服务器进行数据的交互,为此Android的SDK提供了Apache的HttpClient来方便我们使用各种Http服务。你可以把HttpClient想象成一个浏览器,通过它的...

Jonson
2013/07/25
0
3
httpclient DNS cache问题解决办法

DNS缓存在操作系统和JDK内部已经实现了吧,一般不需要再由程序介入了。 the JVM will cache the dns information for me automatically after the first query 也就是说,httpclient去抓取每...

索隆
2012/05/28
0
0

没有更多内容

加载失败,请刷新页面

加载更多

OSX | SafariBookmarksSyncAgent意外退出解决方法

1. 启动系统, 按住⌘-R不松手2. 在实用工具(Utilities)下打开终端,输入csrutil disable, 然后回车; 你就看到提示系统完整性保护(SIP: System Integrity Protection)已禁用3. 输入reboot回车...

云迹
今天
4
0
面向对象类之间的关系

面向对象类之间的关系:is-a、has-a、use-a is-a关系也叫继承或泛化,比如大雁和鸟类之间的关系就是继承。 has-a关系称为关联关系,例如企鹅在气候寒冷的地方生活,“企鹅”和“气候”就是关...

gackey
今天
4
0
读书(附电子书)|小狗钱钱之白色的拉布拉多

关注公众号,在公众号中回复“小狗钱钱”可免费获得电子书。 一、背景 之前写了一篇文章 《小狗钱钱》 理财小白应该读的一本书,那时候我才看那本书,现在看了一大半了,发现这本书确实不错,...

tiankonguse
今天
4
0
Permissions 0777 for ‘***’ are too open

异常显示: @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ WARNING: UNPROTECTED PRIVATE KEY FILE! @ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ......

李玉长
今天
5
0
区块链10年了,还未落地,它失败了吗?

导读 几乎每个人,甚至是对通证持怀疑态度的人,都对区块链的技术有积极的看法,因为它有可能改变世界。然而,区块链技术问世已经10年了,我们仍然没有真正的用上区块链技术。 几乎每个人,甚...

问题终结者
今天
4
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部