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;
/**
* 发送请求
*
*
*/
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 );
}
}
package com.li.bean;
import java.util.HashMap;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
/**
* 封住请求返回的参数
*
*
*/
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;
}
}
package com.li.utli;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 根据正则从HTML中提取响应的数据
*
*
*/
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 ?
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;
/**
* 百度贴吧的发帖及其回贴
*
*
*/
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" , null , null , "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;
}
}
HttpClient4之模拟http请求
原创
©著作权归作者所有:来自51CTO博客作者wbj0110的原创作品,请联系作者获取转载授权,否则将追究法律责任
上一篇:Quartz任务调度
下一篇:PHP 常用的反射函数
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
Java发送Http请求(HttpClient)
文章目录一、简介1、HttpClient2、HTTP协议的特点如下3、使用HttpClient发送请求、接收响应很简单,一般需要如下几步即
java httpclient post http apache -
HttpClient4登陆有验证码的网站
其实就这个问题,本来是很简单的,我自己花了近两个下午才搞定,现在记录一下。也希望能
java apache 验证码