httpclient4.3登陆百度登陆不上

发布于 2021-11-26 04:14:06 字数 4645 浏览 923 评论 7

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 *
 * @author hbj
 */
public class LoginBaidu {

    CloseableHttpResponse execute;
    CloseableHttpClient client;
    HttpPost post = new HttpPost("https://passport.baidu.com/v2/?login");
    HttpGet get = new HttpGet("https://passport.baidu.com/v2/api/?getapi&class=login&tpl=mn&tangram=true");
    HttpGet get1 = new HttpGet("http://www.baidu.com");

    public void login() throws IOException {
        createClient();
        execute = client.execute(get);
        InputStream is = execute.getEntity().getContent();
        Charset charset = ContentType.getOrDefault(execute.getEntity()).getCharset();
        System.out.println(charset);
        BufferedReader br = new BufferedReader(new InputStreamReader(is, charset));
        String line = null;
        while ((line = br.readLine()) != null) {
            if (line.contains("login_token")) {
                line = line.substring(line.indexOf("='") + 2, line.indexOf("';"));
                postLogin(line);
                break;
            }
        }
        execute = client.execute(post);
        System.out.println(execute.getStatusLine().getStatusCode());
        execute = client.execute(get1);
        System.out.println(EntityUtils.toString(execute.getEntity()));
        client.close();
        execute.close();
    }

    public void postLogin(String line) throws UnsupportedEncodingException {
        List<NameValuePair> nvps = new ArrayList<>();
        nvps.add(new BasicNameValuePair("charset", "utf-8"));
        nvps.add(new BasicNameValuePair("codestring", ""));
        nvps.add(new BasicNameValuePair("tpl", "mn"));
        nvps.add(new BasicNameValuePair("index", "0"));
        nvps.add(new BasicNameValuePair("username", "501711499@qq.com"));
        nvps.add(new BasicNameValuePair("password", "14435120"));
        nvps.add(new BasicNameValuePair("token", line));
        nvps.add(new BasicNameValuePair("isPhone", "false"));
        nvps.add(new BasicNameValuePair("loginType", "1"));
        nvps.add(new BasicNameValuePair("mem_pass", "on"));
        nvps.add(new BasicNameValuePair("callback", "parent.bdPass.api.login._postCallback"));
        post.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
    }

    public void createClient() throws IOException {
        HttpClientBuilder create = HttpClientBuilder.create();
        client = create.build();
        execute = client.execute(get1);
//        System.out.println(Arrays.toString(execute.getAllHeaders()));
        Header[] header = execute.getHeaders("Set-Cookie");
//        String s = Arrays.toString(execute.getAllHeaders());
//        s = s.substring(s.indexOf("BAIDUID=")+8, s.indexOf(":FG"));
//        System.out.println(s);
//        BasicClientCookie stdCookie = new BasicClientCookie("BAIDUID", s);
//        stdCookie.setVersion(1);
//        stdCookie.setDomain(".baidu.com");
//        stdCookie.setPath("/");
//        stdCookie.setSecure(true);
//        // Set attributes EXACTLY as sent by the server 
//        stdCookie.setAttribute(ClientCookie.VERSION_ATTR, "1");
//        stdCookie.setAttribute(ClientCookie.DOMAIN_ATTR, ".baidu.com");
//        BasicCookieStore cookieStore = new BasicCookieStore();
//        cookieStore.addCookie(stdCookie);
//        create.setDefaultCookieStore(cookieStore);
        post.setHeaders(header);
        get.setHeaders(header);
        get1.setHeaders(header);
    }

    public static void main(String[] args) throws IOException {
        new LoginBaidu().login();
    }
}
有谁用4.3登陆成功过了吗,求指导啊

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

柳若烟 2021-11-27 06:40:29

/**



* @param username 用户名

* @param password 密码

*
@return 返回验证码图片 (如果有)

*/

public BufferedImage loginBaidu(String username,String password,String codeNum)

{

//cookieStore.clear();

HttpResponse response=null;

HttpEntity entity=null;

this.username=username;

int num=0;

String token=null;

//先用Get请求访问百度主页拿到BAIDUID等相关cookie

HttpGet get_main=new HttpGet(baiduMainUrl);

try {

response=httpClient.execute(get_main,localContext);

//每次执行完一个请求 必须消耗实体内容或者 也可以中断请求 使得连接可以释放

get_main.abort();

HttpGet get_token=new HttpGet(getLoinTokenUrl);

response=httpClient.execute(get_token,localContext);

entity=response.getEntity();

String input=EntityUtils.toString(entity);

ArrayList<String> list=HttpTool.myRegex("[0-9a-z]{32}",input );

if(list.size()!=1)

{

throw new ClientProtocolException("获取token失败 登录无法继续进行");

}

token=list.get(0);

//构造表单数据

List<NameValuePair> params = new ArrayList<NameValuePair>();

if(codeNum!=null&&!codeNum.equals("")) //有验证码时需要额外加几个参数 

{

params.add(new BasicNameValuePair("staticpage","http://www.baidu.com/cache/user/html/v3Jump.html"));

params.add(new BasicNameValuePair("charset","utf-8"));

params.add(new BasicNameValuePair("codestring","captchaservice"+codenum));

params.add(new BasicNameValuePair("verifycode",codeNum));

params.add(new BasicNameValuePair("callback","parent.bd__pcbs__fv6g3o"));

params.add(new BasicNameValuePair("mem_pass","on"));

}

params.add(new BasicNameValuePair("username",username));

params.add(new BasicNameValuePair("password",password));

params.add(new BasicNameValuePair("token", token));

params.add(new BasicNameValuePair("isPhone", "false"));

params.add(new BasicNameValuePair("quick_user", "0"));

params.add(new BasicNameValuePair("tt", System.currentTimeMillis()+""));

params.add(new BasicNameValuePair("loginmerge", "true"));

params.add(new BasicNameValuePair("logintype", "dialogLogin"));

params.add(new BasicNameValuePair("splogin", "rate"));

params.add(new BasicNameValuePair("mem_pass", "on"));

params.add(new BasicNameValuePair("tpl", "mn"));

params.add(new BasicNameValuePair("apiver", "v3"));

params.add(new BasicNameValuePair("u", "http://www.baidu.com/"));

params.add(new BasicNameValuePair("safeflg", "0"));

params.add(new BasicNameValuePair("ppui_logintime", "43661"));

HttpEntity formEntity=new UrlEncodedFormEntity(params,"UTF-8");

HttpPost post_login=new HttpPost(loginUrl);

post_login.setEntity(formEntity);

response=httpClient.execute(post_login,localContext);

HeaderIterator  it = response.headerIterator();

while (it.hasNext()) {

if(it.next().toString().contains("Set-Cookie"))

{

num++;

}

}

} catch (ClientProtocolException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

String loginInfo=HttpTool.htmlToString(response.getEntity());

//如果登录失败  百度只会写入两个cookie 成功会写入6个,这里是根据写入的cookie数量判断是否登录成功

if(num>2)

{

return null;

}

else  //登录失败可能是验证码问题  再处理一下验证码

{

codenum=HttpTool.mid(loginInfo, "captchaservice", "&");

if(codenum==null) //如果处理后还是没匹配到验证码字符就拋个异常吧让上层调用者看着办

{

throw new RuntimeException("未知错误");

}

else //否则就处理验证码

{

InputStream in=null;

BufferedImage checkImg=null;

codeUrl=codeUrl.replace("%codenum", codenum);

HttpGet get=new HttpGet(codeUrl);

try {

response=httpClient.execute(get,localContext);

entity=response.getEntity();

in=entity.getContent();

checkImg=ImageIO.read(in);

in.close();

} catch (ClientProtocolException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

finally

{

try {

if(in!=null)

in.close();

} catch (IOException e) {

e.printStackTrace();

}

}

return checkImg;

}

}

}

梦中楼上月下 2021-11-27 06:35:49

谢谢了,我放弃了╮(╯_╰)╭

够钟 2021-11-27 02:48:50

百度登录源码,我没用过你那种方式,这是以前写的,不知道现在还能不能用。

public boolean doLogining(String num, String psw) throws Exception {
		boolean logined = false;
		DefaultHttpClient client =  ApiUtil.instance();
		String html = "";
		try {
			client.getParams().setParameter(ClientPNames.COOKIE_POLICY,
					CookiePolicy.BROWSER_COMPATIBILITY);
			client.getParams().setParameter(
					"http.protocol.single-cookie-header", true);
			HttpContext httpContext = new BasicHttpContext();
			httpContext.setAttribute(ClientContext.COOKIE_STORE,
					client.getCookieStore());
			HttpGet get = new HttpGet(
					"http://www.baidu.com/cache/user/html/login-1.2.html");

			get.setHeader("Host", "www.baidu.com");
			HttpResponse resp = client.execute(get, httpContext);
			html = EntityUtils.toString(resp.getEntity());
			HttpGet get2 = new HttpGet(
					"https://passport.baidu.com/v2/api/?getapi&class=login&tpl=mn&tangram=true");
			get2.setHeader("Host", "www.baidu.com");

			HttpResponse resp2 = client.execute(get2, httpContext);

			html = EntityUtils.toString(resp2.getEntity());
			int start = html.indexOf("bdPass.api.params.login_token='")
					+ "bdPass.api.params.login_token='".length();

			String token = html.substring(start, html.indexOf("';", start));
			HttpPost post = new HttpPost(
					"https://passport.baidu.com/v2/api/?login");
			post.setHeader("Host", "passport.baidu.com");
			post.setHeader("Referer",
					"http://www.baidu.com/cache/user/html/login-1.2.html");
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			params.add(new BasicNameValuePair("callback",
					"parent.bdPass.api.login._postCallback"));
			params.add(new BasicNameValuePair("charset", "utf-8"));
			params.add(new BasicNameValuePair("codestring", ""));
			params.add(new BasicNameValuePair("index", "0"));
			params.add(new BasicNameValuePair("isPhone", "false"));
			params.add(new BasicNameValuePair("loginType", "1"));
			params.add(new BasicNameValuePair("mem_pass", "on"));
			params.add(new BasicNameValuePair("password", psw));
			params.add(new BasicNameValuePair("ppui_logintime", "12602"));
			params.add(new BasicNameValuePair("safeflg", "0"));
			params.add(new BasicNameValuePair("staticpage",
					"http://www.baidu.com/cache/user/html/jump.html"));
			params.add(new BasicNameValuePair("token", token));
			params.add(new BasicNameValuePair("tpl", "mn"));
			params.add(new BasicNameValuePair("u", ""));
			params.add(new BasicNameValuePair("username", num));
			params.add(new BasicNameValuePair("verifycode", ""));
			try {
				post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}

			HttpResponse response = null;
			html = null;
			try {

			//	System.out.println("登录提交前的COOKIES:");

				for (Cookie c : client.getCookieStore().getCookies()) {
					if (c.getName().equals("BDUSS") && !c.getValue().equals("")) {
						logined = true;
					}
				}
				response = client.execute(post, httpContext);
				html = EntityUtils.toString(response.getEntity());
				get2.abort();

			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				for (Cookie c : client.getCookieStore().getCookies()) {
					if (c.getName().equals("BDUSS") && !c.getValue().equals("")) {
						logined = true;
					}
				}
			}
			if (logined) {
				try {
					CookieUtil.saveCookieStore(num, APP_ID,
							client.getCookieStore());
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				return true;
			} else {
			//	System.out.println(num + "   baidu 登录失败");
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
		
		}

		return false;
	}

顾挽 2021-11-26 16:17:18

这里面不是吗

千纸鹤带着心事 2021-11-26 15:31:20

这里面不是吗

緦唸λ蓇 2021-11-26 13:30:41

不明header里面没有这些吧

悸初 2021-11-26 06:57:56

加上header里面的参数试试,比如host,reference之类的。

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文