0 0

httpclient 登录新浪微博 成功 但是发不了帖子 急求 解决 5

这个是登录新浪微博 发帖代码  

 

private Log log = LogFactory.getLog(Sina.class);

    /**
     * @param args
     */
    public static void main(String[] args) {

        W_self_accounts w_user = new W_self_accounts();
        w_user.setW_useruame_sl("qq312238436");
        w_user.setW_password("201314");
        Sina sina = new Sina();
        
        sina.login(w_user);
        
    }

    /**
     * 登录验证
     * 
     * @param weibuserinfo
     */
    private String ssoLogin(W_self_accounts weibuserinfo, String chkCode) {
        // 获取server time nice
        log.info("ssoLogin");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new NameValuePair("useticket", "1"));
        nvps.add(new NameValuePair("ssosimplelogin", "1"));
        nvps.add(new NameValuePair("su", encodeAccount(weibuserinfo.getW_useruame_sl())));
        nvps.add(new NameValuePair("service", "miniblog"));
        nvps.add(new NameValuePair("servertime", weibuserinfo.getServerTime()));
        nvps.add(new NameValuePair("nonce", weibuserinfo.getNoce()));
        nvps.add(new NameValuePair("pwencode", "wsse"));
        nvps.add(new NameValuePair("sp", new SinaSSOEncoder().encode(weibuserinfo.getW_password(), weibuserinfo.getServerTime(), weibuserinfo.getNoce())));
        nvps.add(new NameValuePair("url", "http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack"));
        nvps.add(new NameValuePair("returntype", "META"));
        nvps.add(new NameValuePair("encoding", "UTF-8"));
        nvps.add(new NameValuePair("client=", "ssologin.js(v1.3.19)"));
        // 验证码
        nvps.add(new NameValuePair("vsnval", chkCode));
        nvps.add(new NameValuePair("entry", "weibo"));
        nvps.add(new NameValuePair("gateway", "1"));
        nvps.add(new NameValuePair("from", ""));
        nvps.add(new NameValuePair("savestate", "7"));
        nvps.add(new NameValuePair("useticket", "1"));
        nvps.add(new NameValuePair("ssosimplelogin", "1"));
        nvps.add(new NameValuePair("returntype", "META"));
        nvps.add(new NameValuePair("encoding", "UTF-8"));
        // ?client=ssologin.js(v1.3.19)
        String entity = WebRuquest.post("http://login.sina.com.cn/sso/login.php", nvps, "");

        return entity;
    }

    public void login(W_self_accounts weibuserinfo) {
        // 获取登录需要的参数
        preLogin(weibuserinfo);
        // 登录
        String entity = ssoLogin(weibuserinfo, "");
        if (StringUtils.isBlank(entity) || StringUtils.isEmpty(entity)) {
            log.info(weibuserinfo.getW_useruame_sl() + "登录失败,请检查网络");
            return;
        }
        if (entity.indexOf("retcode=0") != -1) {// 登录成功
            ajaxLogin(entity, weibuserinfo);
            home(weibuserinfo);
        } else if (entity.indexOf("retcode=4049") != -1) {
            log.info(weibuserinfo.getW_useruame_sl() + "需要验证");
            ImageDialog dialog = new ImageDialog();
            // while (true) {
            // String img = "http://login.sina.com.cn/cgi/pin.php?r=" + (new
            // Random().nextInt()) + "&s=0&p=" + weibuserinfo.getPcid();
            // dialog.setUrl(img);
            // dialog.setUserName(weibuserinfo.getW_useruame_sl());
            // dialog.setVisible(true);
            // dialog.show();
            // // 此句会阻塞
            // System.out.println("测试 阻塞000000000 +=========");
            // String code = dialog.getCode();
            // System.out.println("测试 阻塞 1111111+=========code:" + code);
            // String chkCode = "&pcid=" + weibuserinfo.getPcid() + "&door=" +
            // code;
            // double serverTime =
            // Double.parseDouble(weibuserinfo.getServerTime()) + 40.0;
            // String nonce = makeNonce(6);
            // weibuserinfo.setNoce(nonce);
            // weibuserinfo.setServerTime(serverTime + "");
            // entity = ssoLogin(weibuserinfo, chkCode);
            // System.out.println("++++++++++++++++++++");
            // System.out.println(entity);
            // System.out.println("++++++++++++++++++++");
            // dialog.isOk = false;
            // if (entity.indexOf("retcode=0") != -1) {
            // log.info("break");
            // break;
            // }
            // }
        } else {
            ajaxLogin(entity, weibuserinfo);
        }
    }

    /**
     * 获取登录所需要参数 获取 servertime,nonce
     * 
     * @param weibUserInfo
     */
    private void preLogin(W_self_accounts weibUserInfo) {
        log.info("preLogin");
        String loginName = weibUserInfo.getW_useruame_sl();
        String encodeName;
        try {
            encodeName = URLEncoder.encode(encodeAccount(loginName), "utf-8");
        } catch (UnsupportedEncodingException e) {
            encodeName = encodeAccount(loginName);
        }
        String url = "http://login.sina.com.cn/sso/prelogin.php?entry=miniblog&callback=sinaSSOController.preloginCallBack";
        url += "&user=" + encodeName;
        url += "&client=ssologin.js(v1.3.16)";
        String requestHtml = WebRuquest.post(url, null, "");
        log.info(requestHtml);
        weibUserInfo.setServerTime(JsonUtils.getKey(requestHtml, "servertime"));
        weibUserInfo.setNoce(JsonUtils.getKey(requestHtml, "nonce"));
        weibUserInfo.setPcid(JsonUtils.getKey(requestHtml, "pcid"));
    }

    /**
     * 此次为最后一次登录用来获取cookie
     * 
     * @param weibUserInfo
     */
    private void ajaxLogin(String entity, W_self_accounts weibUserInfo) {
        log.info("ajaxLogin");
        entity = entity.substring(entity.indexOf("location.replace(") + "location.replace(".length() + 1);
        String url = entity.substring(0, entity.indexOf(");") - 1);
        entity = WebRuquest.getOfCookie(url, weibUserInfo);
        if (entity.indexOf("CallBack({") != -1) {
            if ("true".equals(JsonUtils.getKey(entity, "result"))) {
                System.out.println(JsonUtils.getKey(entity, "userinfo"));
                JSONObject userinfo = JSONObject.fromObject(JsonUtils.getKey(entity, "userinfo"));
                weibUserInfo.setW_displayname(userinfo.optString("displayname", ""));
                log.info(weibUserInfo.getW_displayname());
                log.info(userinfo.optString("displayname", ""));
                weibUserInfo.setW_userdomain(userinfo.optString("userdomain", ""));
                weibUserInfo.setW_account_id(userinfo.optString("uniqueid", ""));
                weibUserInfo.setW_useruame_sl(userinfo.optString("userid", ""));
                CacheUser.Add(weibUserInfo);
                sendWeibo(weibUserInfo);
            } else {
                log.info("帐号:" + weibUserInfo.getW_useruame_sl() + JsonUtils.getKey(entity, "reason"));
            }
        }
    }

    private void home(W_self_accounts weibUserInfo) {
        log.info("home");
        String url = "http://www.weibo.com/u/";
        url += weibUserInfo.getW_account_id() + "?" + weibUserInfo.getW_userdomain();
        String html = WebRuquest.get(url, weibUserInfo);
        if (null == html) {
            log.info("网络异常,无法访问url");
        } else {
            if (html.indexOf("你当前使用的帐号异常,请完成手机验证,提升帐号安全") != -1) {
                log.info("你当前使用的帐号异常,请完成手机验证,提升帐号安全");
            } else {
                WeiBoHeper.getInstane().UpdateUserInfo(weibUserInfo, html);
            }
        }
    }

    private void sendWeibo(W_self_accounts user) {
        log.info("sdfdf");
        // List<org.apache.commons.httpclient.Cookie> wbCookie =
        // userlist.get(i).cookies;
        String url = "http://picupload.service.weibo.com/interface/pic_upload.php?cb=";
        String referer = "http://weibo.com/u/" + user.getW_account_id();

        String str3 = "";
        
        url = "http://weibo.com/aj/mblog/add?__rnd=" + RandomUtils.nextInt();
    
        String str6 = "", oldContent = "";
        String sendMsg = " 程序test 微博!!!!!!!";
        if (null != sendMsg) {
            try {
                str6 = URLEncoder.encode(sendMsg, "utf-8");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            oldContent = sendMsg;
        }

        // String requestParam = "_t=0&location=home&module=stissue&pic_id="
        // + str3 + "&text=" + str6;

        List<NameValuePair> paramlist = new ArrayList<NameValuePair>();
        paramlist.add(new NameValuePair("_t", "0"));
        paramlist.add(new NameValuePair("location", "home"));
        paramlist.add(new NameValuePair("module", "stissue"));
        paramlist.add(new NameValuePair("pic_id", str3));
        paramlist.add(new NameValuePair("text", str6));
        paramlist.add(new NameValuePair("_surl", ""));
        paramlist.add(new NameValuePair("rank", ""));
        log.info(user.cookieStr);

        String jsonString = WebRuquest.post(url, paramlist, user.cookieStr, "");
        log.info(jsonString);
        if (JsonUtils.getKey(jsonString, "code").equals("100000")) {
            log.info(user.getW_useruame_sl() + "成功发表微博。" + ((oldContent.length() > 20) ? (oldContent.substring(0, 20) + "...") : oldContent));
        } else if (JsonUtils.getKey(jsonString, "code").equals("100027")) {
            log.info(user.getW_useruame_sl() + "发微博失败。不要太贪心哦,发一次就够啦!" + JsonUtils.getKey(jsonString, "msg"));
        } else {
            log.info(user.getW_useruame_sl() + "发微博失败。" + JsonUtils.getKey(jsonString, "msg"));
            log.info(user.getW_useruame_sl() + "发微博失败。返回内容:" + jsonString);
        }

    }

    /**
     * 用户名 base64 编码
     * 
     * @param account
     * @return
     */
    private static String encodeAccount(String account) {
        String userName = "";
        try {
            userName = Base64.encodeBase64String(URLEncoder.encode(account, "UTF-8").getBytes());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return userName;
    }

    /**
     * 生成 Nonce 这个值应该从服务器获取
     * 
     * @param len
     * @return
     */
    private static String makeNonce(int len) {
        String x = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        String str = "";
        for (int i = 0; i < len; i++) {
            str += x.charAt((int) (Math.ceil(Math.random() * 1000000) % x.length()));
        }
        return str;
    }

    /**
     * 生成 ServerTime 这个值应该从服务器获取
     * 
     * @param len
     * @return
     */
    private static String getServerTime() {
        long servertime = new Date().getTime() / 1000;
        return String.valueOf(servertime);
    }

 

 

下面是 httpclient 访问类

 

package com.deelon.weibo.common;

import java.util.List;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.cookie.CookieSpec;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.deelon.model.W_self_accounts;

public class WebRuquest {
    static Log Logger = LogFactory.getLog(WebRuquest.class);
    private static HttpClient client;

    public static HttpClient getClient() {
        if (client == null) {
            client = new HttpClient();
            client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
            client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
            client.getParams().getDefaults().setBooleanParameter(HttpMethodParams.SINGLE_COOKIE_HEADER, true);
            client.getParams().setBooleanParameter(HttpMethodParams.SINGLE_COOKIE_HEADER, true);
        }
        return client;
    }

    public static String post(String url, List<NameValuePair> heads, String cookies, String str) {
        return post(url, heads, cookies);
    }

    public static synchronized String post(String url, List<NameValuePair> heads, String cookies) {
        Logger.info(url);
        PostMethod post = new PostMethod(url);
        try {
            NameValuePair[] a = new NameValuePair[0];
            post.addRequestHeader("Content-Type","application/x-www-form-urlencoded");
            if (null != heads) {
                a = new NameValuePair[heads.size()];
                heads.toArray(a);
            }
            post.addParameters(a);
            if (StringUtils.isBlank(cookies) && StringUtils.isEmpty(cookies)) {
                post.addRequestHeader("cookie", cookies);
            }
            int statusCode = getClient().executeMethod(post);
            String entity = "";
            Header head = post.getResponseHeader("Set-cookie");
            Logger.info("post:" + head);
            if (statusCode == HttpStatus.SC_OK) {
                entity = post.getResponseBodyAsString();
            }
            Logger.info(entity);
             showCookie("");
            return entity;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            post.releaseConnection();
        }
        return null;
    }

    public static synchronized String get(String url, W_self_accounts w_self_accounts) {
        GetMethod get = new GetMethod(url);
        try {
            if (null != w_self_accounts) {
                if (null != w_self_accounts.getCookies()) {
                    for (int i = 0; i < w_self_accounts.getCookies().size(); i++) {
                        get.addRequestHeader(w_self_accounts.getCookies().get(i).getName(), w_self_accounts.getCookies().get(i).getValue());
                    }
                }
                if (StringUtils.isBlank(w_self_accounts.getCookieStr()) && StringUtils.isEmpty(w_self_accounts.getCookieStr())) {
                    get.addRequestHeader("cookice", w_self_accounts.getCookieStr());
                }
            }
            get.addRequestHeader("cookie", "U_TRS1=00000021.8537292e.504d708e.0e241dbb; path=/; expires=Thu, 08-Sep-22 04:46:06 GMT; domain=.sina.com.cn, U_TRS2=00000021.8546292e.504d708e.25b18021; path=/; domain=.sina.com.cn");
            int statusCode = getClient().executeMethod(get);
            String entity = "";
            Logger.info(statusCode);
            if (statusCode == HttpStatus.SC_OK) {
                entity = get.getResponseBodyAsString();
            }
            // Logger.info(get.getResponseBodyAsString());
            // Header head = get.getResponseHeader("Set-cookie");
            // Logger.info(head);
            // showCookie();
            return entity;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            get.releaseConnection();
        }
        return null;
    }

    /**
     * ge
     * 
     * @param url
     * @param w_self_accounts
     * @param list
     * @return
     */
    public static synchronized String getOfCookie(String url, W_self_accounts w_self_accounts) {
        GetMethod get = new GetMethod(url);
        try {
            if (null != w_self_accounts.getCookies()) {
                for (int i = 0; i < w_self_accounts.getCookies().size(); i++) {
                    get.addRequestHeader(w_self_accounts.getCookies().get(i).getName(), w_self_accounts.getCookies().get(i).getValue());
                }
            }
            int statusCode = getClient().executeMethod(get);
            String entity = "";
            if (statusCode == HttpStatus.SC_OK) {
                entity = get.getResponseBodyAsString();
            }
            // Logger.info(get.getResponseBodyAsString());
            Header head = get.getResponseHeader("Set-cookie");
            w_self_accounts.setCookieStr(head.getValue());
            Logger.info(head);
            Logger.info("--------------------");
            showCookie("");
            Logger.info("===========================================");
            return entity;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            get.releaseConnection();
        }
        return null;
    }

    public static String UploadFile(String url, String filePath, String formFieldName, String contentType, String cookies, String referer) {
        String str = "";
        PostMethod post = null;
        try {
            java.io.File info = new java.io.File(filePath);
            if (!info.exists()) {
                Logger.debug("无法上传图片,找不到文件" + info);
                return str;
            }
            Logger.debug(String.format("Uploading {0}  {1}", filePath, url));
            String str2 = "\r\n-----------------------------" + System.currentTimeMillis() + "\r\n";
            byte[] bytes = str2.getBytes("ASCII");
            // ;Encoding.ASCII.GetBytes("\r\n--" + str2 + "\r\n");
            post = new PostMethod(url);
            if (StringUtils.isBlank(cookies) && StringUtils.isEmpty(cookies)) {
                post.addRequestHeader("cookice", cookies);
            }
            Part[] parts = {new FilePart(info.getName(), info) };
            post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
            // post.addRequestHeader(new Header().)
            int statuscode = getClient().executeMethod(post);
            if (statuscode == HttpStatus.SC_OK) {
                Logger.info("上传成功");
                str = post.getRequestHeader("Location").getValue();
            }else{
                Logger.info("上传失败! 状态吗:" + statuscode);
            }
            Header head = post.getRequestHeader("Set-Cookie");
            Logger.info("upload:" + head.getValue());
            // showCookie();
        } catch (Exception exception) {
            Logger.info(exception);
            Logger.info("图片上传失败:" + exception.getMessage());
        } finally {
            if (null != post) {
                post.releaseConnection();
            }
        }
        Logger.debug("Header Location value:" + str);
        if (!StringUtils.isBlank(str) && !StringUtils.isEmpty(str)) {
            int index = str.indexOf("&pid=");
            if (index != -1) {
                str = str.substring(index + "&pid=".length());
                str = str.substring(0, str.indexOf("&"));
            }
        }
        return str;
    }

    private static void showCookie(String str) {
        // 查看 cookie 信息
        Logger.info("------------------getClient().getState().getCookies();-----------------");
        CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
//        getClient().getState().setC
        Cookie[] cookies= getClient().getState().getCookies();
        for (int i = 0; i < cookies.length; i++) {
            Logger.info(cookies[i]);
        }
        Logger.info("----------------end--getClient().getState().getCookies();-----------------");
        Logger.info("------------------weibocookies-----------------");
        Cookie[] weibocookies = cookiespec.match(Contants.LOGON_SITE, Contants.LOGON_PORT, "/", false, client.getState().getCookies());
        if (weibocookies.length == 0) {
            Logger.info("无weibocookies");
        } else {
            for (int i = 0; i < weibocookies.length; i++) {
                Logger.info(weibocookies[i].getName() + " : " + weibocookies[i].toString());
            }
        }
        Logger.info("-----------end -------weibocookies-----------------");
        Logger.info("---------------sinaCookies-----------------");
        Cookie[] sinaCookies = cookiespec.match("sina.com", Contants.LOGON_PORT, "/", false, client.getState().getCookies());
        if (weibocookies.length == 0) {
            Logger.info("无sinaCookies");
        } else {
            for (int i = 0; i < sinaCookies.length; i++) {
                Logger.info(sinaCookies[i].getName() + " : " + sinaCookies[i].getValue());
            }
        }
        Logger.info("-----------end -------sinaCookies-----------------");
    }

}
2012年9月10日 23:00

2个答案 按时间排序 按投票排序

0 0

楼主解决了吗?求完整的代码

2013年3月04日 10:12
0 0

代码太长了..懒得看,lz直接贴错误吧,话说lz是通过cookie登陆的?没看懂验证码图片处理

2012年9月11日 11:38

相关推荐

Global site tag (gtag.js) - Google Analytics