HttpClient4之模拟http请求

来源:互联网 发布:无声告白 知乎 编辑:程序博客网 时间:2024/05/20 03:43
我来给大家分享使用HttpClient4来模拟http请求,
      本来想用csdn作为实验的,但是害怕版主删帖,所以我就来模拟百度贴吧的登录和回吧。
废话不多说看代码看注释吧。。。

Java code
?
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
package com.li.utli;
 
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
 
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
 
import com.li.bean.Result;
 
/**
 * 发送请求
 * @author Legend、
 *
 */
 
public class SendRequest {
    
    //这是模拟get请求
    public static Result sendGet(String url,Map<String,String> headers,Map<String,String>  params,String encoding,boolean duan) throws ClientProtocolException, IOException{
    //实例化一个Httpclient的
        DefaultHttpClient client = new DefaultHttpClient();
        //如果有参数的就拼装起来
        url = url+(null==params?"":assemblyParameter(params));
        //这是实例化一个get请求
        HttpGet hp = new HttpGet(url);
        //如果需要头部就组装起来
        if(null!=headers)hp.setHeaders(assemblyHeader(headers));
        //执行请求后返回一个HttpResponse
        HttpResponse response = client.execute(hp);
        //如果为true则断掉这个get请求
        if(duan) hp.abort();
        //返回一个HttpEntity
        HttpEntity  entity = response.getEntity();
        //封装返回的参数
        Result result= new Result();
        //设置返回的cookie
        result.setCookie(assemblyCookie(client.getCookieStore().getCookies()));
        //设置返回的状态
        result.setStatusCode(response.getStatusLine().getStatusCode());
        //设置返回的头部信心
        result.setHeaders(response.getAllHeaders());
        //设置返回的信息
        result.setHttpEntity(entity);
        return result;
    }
    public static Result sendGet(String url,Map<String,String> headers,Map<String,String>  params,String encoding) throws ClientProtocolException, IOException{
        return sendGet(url, headers, params, encoding,false);
    }
     
    //这是模拟post请求
    public static Result sendPost(String url,Map<String,String> headers,Map<String,String>  params,String encoding) throws ClientProtocolException, IOException{
        //实例化一个Httpclient的
        DefaultHttpClient client = new DefaultHttpClient();
        //实例化一个post请求
        HttpPost post = new HttpPost(url);
         
        //设置需要提交的参数
        List<NameValuePair> list  = new ArrayList<NameValuePair>();
        for (String temp : params.keySet()) {
            list.add(new BasicNameValuePair(temp,params.get(temp)));
        }
        post.setEntity(new UrlEncodedFormEntity(list,encoding));
         
        //设置头部
        if(null!=headers)post.setHeaders(assemblyHeader(headers));
 
        //实行请求并返回
        HttpResponse response = client.execute(post);
        HttpEntity  entity = response.getEntity();
         
        //封装返回的参数
        Result result = new Result();
        //设置返回状态代码
        result.setStatusCode(response.getStatusLine().getStatusCode());
        //设置返回的头部信息
        result.setHeaders(response.getAllHeaders());
        //设置返回的cookie信心
        result.setCookie(assemblyCookie(client.getCookieStore().getCookies()));
        //设置返回到信息
        result.setHttpEntity(entity);
        return result ;
    }
     
    //这是组装头部
    public static Header[] assemblyHeader(Map<String,String> headers){
        Header[] allHeader= new BasicHeader[headers.size()];
        int i  = 0;
        for (String str :headers.keySet()) {
            allHeader[i] = new BasicHeader(str,headers.get(str));
            i++;
        }
        return allHeader;
    }
     
    //这是组装cookie
    public static String assemblyCookie(List<Cookie> cookies){
        StringBuffer sbu = new StringBuffer();
        for (Cookie cookie : cookies) {
            sbu.append(cookie.getName()).append("=").append(cookie.getValue()).append(";");
        }
        if(sbu.length()>0)sbu.deleteCharAt(sbu.length()-1);
        return sbu.toString();
    }
    //这是组装参数
    public static String assemblyParameter(Map<String,String> parameters){
        String para = "?";
        for (String str :parameters.keySet()) {
            para+=str+"="+parameters.get(str)+"&";
        }
        return para.substring(0,para.length()-1);
    }
}

Java code
?
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
package com.li.bean;
 
import java.util.HashMap;
 
import org.apache.http.Header;
import org.apache.http.HttpEntity;
 
/**
 * 封住请求返回的参数
 * @author Legend、
 *
 */
 
public class Result {
     
    private String cookie;
    private int statusCode;
    private HashMap<String, Header> headerAll;
    private HttpEntity httpEntity;
     
    public String getCookie() {
        return cookie;
    }
    public void setCookie(String cookie) {
        this.cookie = cookie;
    }
    public int getStatusCode() {
        return statusCode;
    }
    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }
    public HashMap<String, Header> getHeaders() {
        return headerAll;
    }
     
    public void setHeaders(Header[] headers){
        headerAll = new HashMap<String, Header>();
        for (Header header : headers) {
            headerAll.put(header.getName(), header);
        }
    }
    public HttpEntity getHttpEntity() {
        return httpEntity;
    }
    public void setHttpEntity(HttpEntity httpEntity) {
        this.httpEntity = httpEntity;
    }
}


Java code
?
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
package com.li.utli;
 
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
/**
 * 根据正则从HTML中提取响应的数据
 * @author Legend、
 *
 */
 
public class HtmlParse {
     
    public static List<String> prase(String html,String regex,int number){
         
        Pattern patten = Pattern.compile(regex);
        Matcher mat = patten.matcher(html);
        List<String> list = new ArrayList<String>();
        while(mat.find()) {
       if(number==-1){
           list.add(mat.group());
           continue;
       }
        if(number>0){
            list.add(mat.group());
            number--;
           }else{
               break;
           }
        }
        return list;
    }   
     
    public static List<String> prase(String html,String regex){
        return prase(html, regex, -1);
    }
     
}


Java code
?
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
package com.li.main;
 
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
 
import javax.swing.JOptionPane;
 
import org.apache.http.client.ClientProtocolException;
import org.apache.http.util.EntityUtils;
 
import com.li.bean.Result;
import com.li.utli.HtmlParse;
import com.li.utli.SendRequest;
import com.li.utli.VerificationcCode;
 
/**
 * 百度贴吧的发帖及其回贴
 * @author Legend、
 *
 */
public class BaiduTieBaNDWS {
     
    public static  String reply(String content, String postsUrl,String cookie) throws ClientProtocolException, IOException {
         
         
        //这是一些可有可无的头部信息,有的时候不需要,但是有的时候确需要,所以建议大家最好加上!
        Map<String,String> headers = new HashMap<String,String>();
        headers.put("Referer", postsUrl);
        headers.put("Host""tieba.baidu.com");
        headers.put("Cookie",cookie);
         
        //这是从帖子中获取一些发帖时候必备的参数
        String html = EntityUtils.toString(SendRequest.sendGet(postsUrl, headers, null"utf-8").getHttpEntity(),"utf-8");
         
        String needParametersResolve[] = HtmlParse.prase(html, "kw:'.+',ie:'utf-8',rich_text:'\\d+',floor_num:'\\d+',fid:'\\d+',tid:'\\d+',tfrom:'\\d+',user_type:'\\d+'").get(0).replaceAll("'""").split(",");
         
        String floor_num = needParametersResolve[3].split(":")[1];
        String fid = needParametersResolve[4].split(":")[1];
         
        String tid = needParametersResolve[5].split(":")[1];
        String kw =needParametersResolve[0].split(":")[1];
         
         
        String vk_code = EntityUtils.toString(SendRequest.sendGet("http://tieba.baidu.com/f/user/json_vcode?lm="+fid+"&rs10=2&rs1=0&t=0.5954980056343667"nullnull"utf-8").getHttpEntity(),"utf-8");
        String code = vk_code.split("\"")[7];
        String tbs = EntityUtils.toString(SendRequest.sendGet("http://tieba.baidu.com/dc/common/tbs?t=0.17514605234768638", headers, null"utf-8").getHttpEntity(),"utf-8").split("\"")[3];
         
        //这是下载验证码
        VerificationcCode.showGetVerificationcCode("http://tieba.baidu.com/cgi-bin/genimg?"+code, null,"e:/1.png");
         
        //设置提交所有的参数
        Map<String,String> parameters = new HashMap<String,String>();
        parameters.put("add_post_submit""发 表 ");
        parameters.put("kw", kw);
        parameters.put("floor_num", floor_num);
        parameters.put("ie""utf-8");
        parameters.put("rich_text""1");
        parameters.put("hasuploadpic""0");
        parameters.put("fid",fid);
        parameters.put("rich_text""1");
        parameters.put("tid", tid);
        parameters.put("hasuploadpic""0");
        parameters.put("picsign""");
        parameters.put("quote_id""0");
        parameters.put("useSignName""on");
        parameters.put("content", content);
        parameters.put("vcode_md5", code);
        parameters.put("tbs", tbs);
        parameters.put("vcode", JOptionPane.showInputDialog(null,
                "<html><img src=\"file:///e:/1.png\" width=\33\" height=\55\"><br><center>请输入验证码</center><br></html>"));
         
        //准备好一切,回帖
        Result res = SendRequest.sendPost("http://tieba.baidu.com/f/commit/post/add", headers, parameters, "utf-8");
         
        //回帖之后百度会返回一段json,说明是否回帖成功
        return EntityUtils.toString(res.getHttpEntity(),"utf-8");
    }
 
    //百度登陆
    public static  String testAccount(String name, String password) throws ClientProtocolException, IOException {
        Map<String,String> parameters = new HashMap<String,String>();
        parameters.put("password", password);
        parameters.put("username", name);
            String str = SendRequest.sendPost("https://passport.baidu.com/?login"null, parameters,"utf-8").getCookie();
            return str;
    }
     
}
对我有用[2] 丢个板砖[0] 引用 | 举报 | 管理 | TOP
回复次数:143
#1 得分:0回复于: 2011-08-29 17:05:33
Java code
?
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
package com.li.utli;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
 
/**
 * 下载验证码的
 * @author Legend、
 *
 */
public class VerificationcCode {
    
    //发送post请求获取验证码
    public static void showVerificationcCode(String url,String fileUrl) throws ClientProtocolException, IOException{
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        HttpResponse response = client.execute(post);
        HttpEntity entity = response.getEntity();
        InputStream in= entity.getContent();
        int temp = 0;
        File file = new File(fileUrl);
        FileOutputStream out = new FileOutputStream(file);
        while((temp=in.read())!=-1){
         out.write(temp);
        }
        in.close();
        out.close();
    }
 
    //发送get请求获取验证码
    public static String showGetVerificationcCode(String url,Map<String ,String> header, String fileUrl) throws ClientProtocolException, IOException {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(url);
        if(null!=header&&header.size()>0){
            get.setHeaders(SendRequest.assemblyHeader(header));
        }
        HttpResponse response = client.execute(get);
        HttpEntity entity = response.getEntity();
        InputStream in= entity.getContent();
        int temp = 0;
        File file = new File(fileUrl);
        FileOutputStream out = new FileOutputStream(file);
        while((temp=in.read())!=-1){
         out.write(temp);
        }
        in.close();
        out.close();
        return SendRequest.assemblyCookie(client.getCookieStore().getCookies());
    }
}

最后的主方法:
Java code
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.li.main;
 
/**
 *  主方法
 * @author Legend、
 *
 */
public class BaiduMain {
 
     
public static void main(String[] args) throws Exception {
         
    //验证账号并获取cookie
        String cookie  =  BaiduTieBaNDWS.testAccount("""");
        //发帖
        String info = BaiduTieBaNDWS.reply("这个贴狠牛B啊!!""http://tieba.baidu.com/p/1193625840", cookie);
        //打印返回信心
        System.out.println(info);
    }
}


除了BaiduTieBaNDWS这个类之外,其他的类都可以直接重用。。除了百度贴吧、我们还可以做百度知道,各大论坛的回复,或者可以刷网上投票啊,我想一些网购的秒杀也是一样的,就是发一个请求带上一些必要参数而已。。。小菜第一次发这种技术贴,写的不好之处请大家海涵!