-
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
相关推荐
httpclient4模拟登陆新浪微博 最新版
NULL 博文链接:https://zrzking.iteye.com/blog/1946063
2016年4月7最新新浪微博模拟登录HttpClient4.5.2
此资源为新浪微博和腾讯微博的HttpClient4模拟登录的代码Sina.java为新浪的,TencentClient.java为腾讯的。
* 测试新浪微博API * @author syn * @date 2010/12/22 */ public class TestActivity extends Activity { private static final String BASE_URL = "http://api.t.sina.com.cn/"; //API接口 private static final ...
httpclient方式登陆,以及发布微博
用HttpClient实现了 网易相册的登录
HttpClient模拟登录实例,模拟登录网站,获取用户信息,登录后数据,带验证码登录,带解析HTML实例。
使用HttpClient登录网易邮箱 博文链接:https://bps.iteye.com/blog/136231
模拟登录 不提供用户名密码
许多人只会简单的爬,但是有的网站需要登录就不会弄了,再或者有的网站有验证码也不知道如何处理了,看完这个例子,相信你能有所收获。当然老手肯定会这些,因此该例子针对新人。 发布时间:2018-09-28
新浪微博爬虫,采用Java语言开发,基于HTTPClient 4.0,采用MySQL存储爬取数据,支持多进程并发执行。功能包括:爬取微博、评论、转发、关注列表(层次)。根据数据需求,持续更新....zip可以用于毕业设计(项目源码...
我使用的是httpClient 进行内部转发 我们在A的服务器上,将前台的文件流,通过httpClient传输到B的服务器上(B的服务器通过控制层接受A传输的文件流,让后保存在B的服务器上。返回一个json结果)
NULL 博文链接:https://shaozhen.iteye.com/blog/946680
httpclient
完整的java登录新浪微博并获取登录后网页的工程。内含所需的jar包 commons-io-1.3.2.jar commons-logging-api-1.0.3.jar httpclient-4.0-beta2.jar httpcore-4.1-alpha1.jar
下载这个工具类,然后直接调用createHtmlPage方法就可以了。最关键一点是,网上的方法没有一个解决了乱码问题,费了我不少功夫。