一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服務(wù)器之家 - 編程語言 - JAVA教程 - Java模擬新浪和騰訊自動登錄并發(fā)送微博

Java模擬新浪和騰訊自動登錄并發(fā)送微博

2020-06-01 13:26supercrsky JAVA教程

這篇文章主要為大家詳細介紹了Java模擬新浪和騰訊自動登錄并發(fā)送微博功能,感興趣的小伙伴們可以參考一下

Java模擬新浪和騰訊自動登錄并發(fā)送微博功能分享給大家,供大家參考,具體內(nèi)容如下

1.準備工作
只是登錄無需申請新浪和騰迅的開發(fā)者賬號,如果需要發(fā)送微博功能,需要申請一個新浪和騰迅的開發(fā)者賬號,并添加一個測試應(yīng)用。 

過程請參考官方幫助文檔,申請地址:新浪:http://open.weibo.com    騰迅:http://dev.t.qq.com/

我們需要的是App Key和App Secre及redirect_URI,源代碼中已經(jīng)包含了我申請的測試key,但由于限制直接用我的key你們的賬號是無法登錄成功的。 

2.注意事項
 1)、需要注意的是應(yīng)用的App Key和App Secre及redirect_URI,對應(yīng)項目根目錄下的config.properties配置文件中的
client_ID=1745656892
client_SERCRET=66056719c1d8ca7bcaf36f411217cefa
redirect_URI=www.baidu.com

redirect_URI由于只是測試用并沒有直接的回調(diào)頁面,所以這里隨便填寫一個地址就行了,但要注意與應(yīng)用-高級設(shè)置里的“回調(diào)頁面”一致。 
2)、代碼中的測試賬號需要要自己添加測試賬號,新浪的在“應(yīng)用信息-測試賬號”;騰迅的在“權(quán)限控制-創(chuàng)建白名單”中。當然直接用 開發(fā)者賬號也可以。
3)、發(fā)送微博引用了新浪的weibo4j-oauth2-beta2.1.1.zip,騰迅的Java_SDK_v1.2.1.7z。核心類在util包下。

3.關(guān)鍵代碼
1)、新浪 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package org.utils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
 
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpException;
import org.core.weibo.sina.Oauth;
import org.core.weibo.sina.Timeline;
import org.core.weibo.sina.http.AccessToken;
import org.core.weibo.sina.model.WeiboException;
import org.core.weibo.sina.weibo4j.util.WeiboConfig;
/***
 * 模擬自動登錄并發(fā)微博
 * @author zdw
 *
 */
public class Sina {
 /***
 * 模擬登錄并得到登錄后的Token
 * @param username 用戶名
 * @param password 密碼
 * @return
 * @throws HttpException
 * @throws IOException
 */
 public static AccessToken getToken(String username,String password) throws HttpException, IOException
 {
  String clientId = WeiboConfig.getValue("client_ID") ;
  String redirectURI = WeiboConfig.getValue("redirect_URI") ;
  String url = WeiboConfig.getValue("authorizeURL");
  
  PostMethod postMethod = new PostMethod(url);
  //應(yīng)用的App Key
  postMethod.addParameter("client_id",clientId);
  //應(yīng)用的重定向頁面
  postMethod.addParameter("redirect_uri",redirectURI);
  //模擬登錄參數(shù)
  //開發(fā)者或測試賬號的用戶名和密碼
  postMethod.addParameter("userId", username);
  postMethod.addParameter("passwd", password);
  postMethod.addParameter("isLoginSina", "0");
  postMethod.addParameter("action", "submit");
  postMethod.addParameter("response_type","code");
  HttpMethodParams param = postMethod.getParams();
  param.setContentCharset("UTF-8");
  //添加頭信息
  List<Header> headers = new ArrayList<Header>();
  headers.add(new Header("Referer", "https://api.weibo.com/oauth2/authorize?client_id="+clientId+"&redirect_uri="+redirectURI+"&from=sina&response_type=code"));
  headers.add(new Header("Host", "api.weibo.com"));
  headers.add(new Header("User-Agent","Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0"));
  HttpClient client = new HttpClient();
  client.getHostConfiguration().getParams().setParameter("http.default-headers", headers);
  client.executeMethod(postMethod);
  int status = postMethod.getStatusCode();
  System.out.println(status);
  if (status != 302)
  {
  System.out.println("token刷新失敗");
  return null;
  }
  //解析Token
  Header location = postMethod.getResponseHeader("Location");
  if (location != null)
  {
  String retUrl = location.getValue();
  int begin = retUrl.indexOf("code=");
  if (begin != -1) {
   int end = retUrl.indexOf("&", begin);
   if (end == -1)
   end = retUrl.length();
   String code = retUrl.substring(begin + 5, end);
   if (code != null) {
   Oauth oauth = new Oauth();
   try{
    AccessToken token = oauth.getAccessTokenByCode(code);
    return token;
   }catch(Exception e){
    e.printStackTrace();
   }
   }
  }
  }
 return null;
 }
 /**
 * 發(fā)微博
 * @param token 認證Token
 * @param content 微博內(nèi)容
 * @return
 * @throws Exception
 */
 public static boolean sinaSendWeibo(String token,String content) throws Exception {
 boolean flag = false ;
 Timeline timeline = new Timeline();
 timeline.client.setToken(token);
 try
 {
  timeline.UpdateStatus(content);
  flag = true ;
 }
 catch (WeiboException e)
 {
  flag = false ;
  System.out.println(e.getErrorCode());
 }
 return flag;
 }
 
 public static void main(String[] args) throws Exception
 {
 AccessToken at = getToken("xxxx","xxx");
 sinaSendWeibo(at.getAccessToken(),"測試呢");
 }
}
 

2)、騰迅 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
package org.utils;
 
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.Scanner;
 
import net.sf.json.JSONObject;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.core.weibo.tencent.api.UserAPI;
import org.core.weibo.tencent.oauthv2.OAuthV2;
import org.core.weibo.tencent.oauthv2.OAuthV2Client;
 
/***
 * 騰迅自動登錄并獲取個人信息
 * @author zdw
 *
 */
public class Tencent
{
 public static final String HEXSTRING = "0123456789ABCDEF";
 public static OAuthV2 oAuth = new OAuthV2();
 private static HttpClient client = new DefaultHttpClient();
 // 初始oAuth應(yīng)用信息
 public static void init(OAuthV2 oAuth)
 {
 oAuth.setClientId("801216331");
 oAuth.setClientSecret("ea71b26b0cbe5778cdd1c09ad17553a3");
 oAuth.setRedirectUri("http://www.tencent.com/zh-cn/index.shtml");
 }
 /**
 *
 * @param qq
 *      http://check.ptlogin2.qq.com/check?uin={0}&appid=15000101&r={1 }
 *      返回的第三個值
 * @param password
 *      QQ密碼
 * @param verifycode
 *      驗證碼
 * @return 加密后的密碼
 * @throws UnsupportedEncodingException
 * @throws Exception
 *
 */
 public static String GetPassword(String qq, String password,
  String verifycode) throws Exception
 {
 String P = hexchar2bin(md5(password));
 String U = md5(P + hexchar2bin(qq.replace("\\x", "").toUpperCase()));
 String V = md5(U + verifycode.toUpperCase());
 return V;
 }
 
 public static String md5(String originalText) throws Exception
 {
 byte buf[] = originalText.getBytes("ISO-8859-1");
 StringBuffer hexString = new StringBuffer();
 String result = "";
 String digit = "";
 try
 {
  MessageDigest algorithm = MessageDigest.getInstance("MD5");
  algorithm.reset();
  algorithm.update(buf);
  byte[] digest = algorithm.digest();
  for (int i = 0; i < digest.length; i++)
  {
  digit = Integer.toHexString(0xFF & digest[i]);
  if (digit.length() == 1)
  {
   digit = "0" + digit;
  }
  hexString.append(digit);
  }
  result = hexString.toString();
 }
 catch (Exception ex)
 {
  result = "";
 }
 return result.toUpperCase();
 }
 
 public static String hexchar2bin(String md5str) throws UnsupportedEncodingException
 {
 ByteArrayOutputStream baos = new ByteArrayOutputStream(md5str.length() / 2);
 for (int i = 0; i < md5str.length(); i = i + 2)
 {
  baos.write((HEXSTRING.indexOf(md5str.charAt(i)) << 4 | HEXSTRING
   .indexOf(md5str.charAt(i + 1))));
 }
 return new String(baos.toByteArray(), "ISO-8859-1");
 }
 /***
 * 模擬登錄
 * @param qq QQ號碼
 * @param password QQ密碼
 * @throws Exception
 */
 public static void login(String qq, String password) throws Exception
 {
 HttpGet get = new HttpGet("https://ssl.ptlogin2.qq.com/check?uin="+ qq + "&appid=46000101&ptlang=2052&js_type=2&js_ver=10009&r=0.7948186025712065");
 HttpResponse response = client.execute(get);
 String entity = EntityUtils.toString(response.getEntity());
 String[] checkNum = entity.substring(entity.indexOf("(") + 1,entity.lastIndexOf(")")).replace("'", "").split(",");
 String pass = "";
 String responseData = "";
 // 獲取驗證碼(如果有驗證碼輸出到C:/code.jpg,查看后輸入可繼續(xù)執(zhí)行
 if ("1".equals(checkNum[0]))
 {
  // uin為qq號或者微博用戶名
  HttpGet getimg = new HttpGet("http://captcha.qq.com/getimage?aid=46000101&r=0.3478789969909082&uin=" + qq + "&vc_type=" + checkNum[1] + "");
  HttpResponse response2 = client.execute(getimg);
  OutputStream os = new FileOutputStream("c:/code.jpg");
  byte[] b = EntityUtils.toByteArray(response2.getEntity());
  os.write(b, 0, b.length);
  os.close();
  Scanner in = new Scanner(System.in);
  responseData = in.nextLine();
  in.close();
 }
 else
 {
  responseData = checkNum[1];
 }
 /** *******************加密密碼 ************************** */
 pass = GetPassword(checkNum[2], password, responseData);
 /** *********************** 登錄 *************************** */
 HttpGet getimg = new HttpGet("https://ssl.ptlogin2.qq.com/login?ptlang=2052&u="+ qq+ "&p="+ pass+ "&verifycode="+ responseData+ "&aid=46000101&target=top&u1=https%3A%2F%2Fopen.t.qq.com%2Fcgi-bin%2Foauth2%2Fauthorize%3Fclient_id%3D"
   + oAuth.getClientId()+ "%26response_type%3Dcode%26redirect_uri="+ oAuth.getRedirectUri()+ "&ptredirect=1&h=1&from_ui=1&dumy=&qlogin_param=abbfew=ddd&wording=%E6%8E%88%E6%9D%83&fp=loginerroralert&action=8-13-240977&g=1&t=1&dummy=&js_type=2&js_ver=10009");
 HttpResponse response2 = client.execute(getimg);
 HttpEntity httpentity = response2.getEntity();
 String entityxc = EntityUtils.toString(httpentity);
 System.out.println(entityxc);
 }
 
 /**
 *
 * 請求微博開放平臺應(yīng)用 返回登錄授權(quán)頁面,但是如果沒有sessionKey的話永遠登錄不成功 sessionKey
 * 發(fā)現(xiàn)在返回的頁面中一個input標簽里放的url中有,所以要取到這個sessionKey 其實直接訪問標簽中的url就可以跳轉(zhuǎn)
 *
 */
 public static String getUrl() throws ClientProtocolException, IOException
 {
 HttpGet getcode = new HttpGet("https://open.t.qq.com/cgi-bin/oauth2/authorize?client_id="+ oAuth.getClientId()+ "&response_type=code&redirect_uri="
     + oAuth.getRedirectUri()+ "&checkStatus=yes&appfrom=&g_tk&checkType=showAuth&state=");
 HttpResponse response3 = client.execute(getcode);
 HttpEntity entityqqq = response3.getEntity();
 String entityxcc = EntityUtils.toString(entityqqq);
 String form = entityxcc.substring(entityxcc.indexOf("<form"), entityxcc
  .indexOf("</form>"));
 String[] ss = form.split("/>");
 String input = "";
 for (int i = 0; i < ss.length; i++)
 {
  if (ss[i].indexOf("name=\"u1\"") > 0)
  {
  input = ss[i];
  }
  ;
 }
 return input.substring(input.indexOf("value=\"") + 7, input.indexOf("\" type=\""));
 }
 /**
 * 解析并設(shè)置Token
 * @param get
 * @throws Exception
 */
 public static void setToken(HttpGet get) throws Exception
 {
 HttpResponse response4 = client.execute(get);
 HttpEntity entityqqq1 = response4.getEntity();
 String getUrlcode = EntityUtils.toString(entityqqq1);
 // 返回了最終跳轉(zhuǎn)的頁面URL,也就是回調(diào)頁redirect_uri,頁面地址上包含code openid openkey
 // 需要將這三個值單獨取出來再拼接成 code=xxxxx&openid=xxxxx&openkey=xxxxxx的形式
 String entity = getUrlcode.substring(getUrlcode.indexOf("url="),getUrlcode.indexOf("\">"));
 StringBuffer sb = new StringBuffer();
 String[] arr = entity.split("\\?")[1].split("&");
 for (int x = 0; x < arr.length; x++)
 {
  if (arr[x].indexOf("code") >= 0 || arr[x].indexOf("openid") >= 0
   || arr[x].indexOf("openkey") >= 0)
  {
  sb.append(arr[x] + "&");
  }
  ;
 }
 // 利用code獲取accessToken
 OAuthV2Client.parseAuthorization(sb.substring(0, sb.length() - 1), oAuth);
 oAuth.setGrantType("authorize_code");
 OAuthV2Client.accessToken(oAuth);
 }
 /***
 * 調(diào)用(騰迅開放平臺賬戶接口)獲取一個人的信息
 * @throws Exception
 */
 public static void getInfo() throws Exception
 {
 //輸出Token,如果拿到了Token就代表登錄成功,并可以進行下一步操作。
 System.out.println("Token="+oAuth.getAccessToken());
 UserAPI getuser = new UserAPI(oAuth.getOauthVersion());
 String userJson = getuser.otherInfo(oAuth, "json", "", oAuth.getOpenid());
 JSONObject userJsonObject = JSONObject.fromObject(userJson);
 Integer errcode = (Integer) userJsonObject.get("errcode");
 if (errcode == 0)
 {
  JSONObject userdataJsonObject = (JSONObject) userJsonObject.get("data");
  System.out.println(userdataJsonObject.toString());
 }
 }
 
 public static void main(String[] args) throws Exception
 {
 init(oAuth);
 login("123145", "xxxx");
 HttpGet get = new HttpGet(getUrl());
 setToken(get);
 getInfo();
 }
 
 
 
}

4.發(fā)送成功都有對應(yīng)的日志輸出
新浪(最后一行日志):

 2078 DEBUG [2013-03-14 16:35:29]  {"created_at":"Thu Mar 14 16:35:30 +0800 2013","id":3555791132949940,"mid":"3555791132949940","idstr":"3555791132949940","text":"測試呢","source":"...

騰迅:

登錄成功的日志標志: 
ptuiCB('0','0','https://open.t.qq.com/cgi-bin/oauth2/authorize?client_id=801216331&response_type=code&redirect_uri=http:','1','登錄成功!', 'ㄗs:ヤ淡 啶');查看個人信息成功后的日志標志: 

QHttpClient httpGet [3] Response = {"data":{"birth_day":26,"birth_month":8,"birth_year":2011,"city_code":"2","comp":null,"country_code":"1","edu":null,"email":"","exp":141,"fansnum":..

日志未全列出,只是作為參考。

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持服務(wù)器之家。

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 91视频破解版 | 99手机在线视频 | 亚洲欧美成人综合久久久 | 日韩在线中文字幕 | 亚洲欧美日韩综合在线 | 四虎国产精品免费久久麻豆 | 亚洲第一网站免费视频 | 国产卡一卡二卡三乱码手机 | 妇伦小说 | 日本老熟老太hd | 欧美白人猛性xxxxx69交 | 秋霞啪啪网| 日韩欧美一区二区三区四区 | 紧身裙女教师波多野结衣 | 武侠古典久久亚洲精品 | 公妇乱淫在线播放免费观看 | 四虎成人免费大片在线 | 国产一区二区不卡 | 污文啊好棒棒啊好了 | 国产成人免费视频 | 男人扒开 | 毛片在线观看网站 | 韩国黄色网址 | 国色天香视频完整版 | 亚洲第一综合网站 | 青青草视频国产 | 国产日韩欧美色视频色在线观看 | 婷婷色综合网 | 色噜噜视频影院 | 爽好舒服快想要免费看 | 青青草一区二区免费精品 | 日韩专区在线观看 | 精品国产日韩亚洲一区在线 | 色婷婷综合和线在线 | 1313午夜精品久久午夜片 | 亚洲26uuuu最新地址 | 亚洲视屏在线观看 | 亚洲精品国精品久久99热 | 11 13加污女qq看他下面 | 亚洲福利视频在线观看 | 男人的天堂视频 |