君子博学而日参省乎己 则知明而行无过矣

博客园 首页 新随笔 联系 订阅 管理

 SingletonClient.getHttpClient().execute(post2,localContext);这里是采用httpclient组件提交http请求,需要导入相应的依赖

<!-- httpclient -->
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.2.1</version>
    </dependency>
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpcore</artifactId>
      <version>4.2.1</version>
    </dependency>
    
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpmime</artifactId>
      <version>4.2.1</version>
    </dependency>
    
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient-cache</artifactId>
      <version>4.2.1</version>
    </dependency>
    
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>fluent-hc</artifactId>
      <version>4.2.1</version>
    </dependency>
    
    <dependency>
      <groupId>commons-codec</groupId>
      <artifactId>commons-codec</artifactId>
      <version>1.6</version>
    </dependency>

    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version>1.1.1</version>

    </dependency> 

工具类SingletonClient.java

 public class SingletonClient {    

     
    private static final String CHARSET = "UTF-8";  
    private static HttpClient singleHttpClient;  
  
    private SingletonClient() {  
    }  
  
    public static synchronized HttpClient getHttpClient() {  
        if (null == singleHttpClient) {  
            //exe = Executors.newFixedThreadPool(POOL_SIZE);
            
            HttpParams params = new BasicHttpParams();  
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);  
            HttpProtocolParams.setContentCharset(params, CHARSET);  
            HttpProtocolParams.setUseExpectContinue(params, true);  
            HttpProtocolParams  
                    .setUserAgent(  
                            params,  
                            "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 GTB6 (.NET CLR 3.5.30729)");           
            /* 连接超时 */  
            HttpConnectionParams.setConnectionTimeout(params, 5000);  
            /* 请求超时 */  
            HttpConnectionParams.setSoTimeout(params, 5000);  
  
            // 设置HttpClient支持的请求模式  
            SchemeRegistry schReg = new SchemeRegistry();  
            schReg.register(new Scheme("http", 80, PlainSocketFactory  
                    .getSocketFactory()));  
            schReg.register(new Scheme("https", 443, SSLSocketFactory  
                    .getSocketFactory()));  
            // 在最新版本的httpclient中ThreadSafeClientConnManager已被@Deprecated掉,这里使用PoolingClientConnectionManager。  
            
//ClientConnectionManager conMgr = new PoolingClientConnectionManager(schReg);  
            PoolingClientConnectionManager conMgr = new PoolingClientConnectionManager(schReg);  
            conMgr.setMaxTotal(10);
            //HttpHost localhost = new HttpHost("locahost", 80);
            
//conMgr.setMaxPerRoute(new HttpRoute(localhost), 50);
            
            singleHttpClient = new DefaultHttpClient(conMgr, params);
            
        }  
        return singleHttpClient;  
    }
}

UserContext .java

public class UserContext {

    /**
     * 
@param args
     
*/
    public static void main(String[] args) {
        // TODO Auto-generated method stub        
        final HttpContext localContext=initContext();        
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

         List<BasicNameValuePair> list2= new ArrayList<BasicNameValuePair>();
            list2.add(new BasicNameValuePair("__VIEWSTATE","/wEPDwUJNDYwODU2NjU1ZGQ="));            
            list2.add(new BasicNameValuePair("txbComment","我跟你拼了  哈哈"));
            list2.add(new BasicNameValuePair("btnSubmint","提交评论"));
             final HttpPost post2=SingletonClient.getPost("http://m.cnblogs.com/mobileAddComment.aspx?id=101461&entry=2733027", list2);
             
            Thread mythread=new Thread(new Runnable(){
             int minute=59;
             int second=16;
             int millisec=400;
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    SimpleDateFormat sdf2=new SimpleDateFormat("yyyy年MM月dd日hh时mm分ss秒SSS毫秒");
                    //int sec=0;
                    while(true)
                    {
                        
                        if(Calendar.getInstance().get(Calendar.MINUTE)==minute&&Calendar.getInstance().get(Calendar.SECOND)==second&&Calendar.getInstance().get(Calendar.MILLISECOND)>millisec)
                        {
                            try {
                                long start=System.currentTimeMillis();                                
                                HttpResponse httpResponse1 = SingletonClient.getHttpClient().execute(post2,localContext);
                                System.out.println("响应代码1"+httpResponse1.getStatusLine().getStatusCode());
                                long end=System.currentTimeMillis();
                                System.out.println("往返响应时间:"+(end-start));                                
                                break;
                                
                            } catch (ClientProtocolException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }                                
                            break;                            
                        }
                        System.out.println(sdf2.format(new Date()));
                        
                    }
                    
                }
                
            });            
            mythread.start();
    }
    public static HttpContext initContext()
    {
        List<BasicNameValuePair> list= new ArrayList<BasicNameValuePair>();    
        
        list.add(new BasicNameValuePair("__EVENTTARGET",""));
        list.add(new BasicNameValuePair("__EVENTARGUMENT",""));
        list.add(new BasicNameValuePair("__VIEWSTATE","/wEPDwULLTE1MzYzODg2NzZkGAEFHl9fQ29udHJvbHNSZXF1aXJlUG9zdEJhY2tLZXlfXxYBBQtjaGtSZW1lbWJlcm1QYDyKKI9af4b67Mzq2xFaL9Bt"));
        list.add(new BasicNameValuePair("__EVENTVALIDATION","/wEWBQLWwpqPDQLyj/OQAgK3jsrkBALR55GJDgKC3IeGDE1m7t2mGlasoP1Hd9hLaFoI2G05"));
        list.add(new BasicNameValuePair("tbUserName","你的用户名"));
        list.add(new BasicNameValuePair("tbPassword","你的密码"));
        list.add(new BasicNameValuePair("btnLogin","登录"));
        
        HttpPost post=SingletonClient.getPost("http://passport.cnblogs.com/login.aspx", list);
        
        // 创建一个本地Cookie存储的实例  
        CookieStore cookieStore = new BasicCookieStore();  
        //创建一个本地上下文信息  
        HttpContext localContext = new BasicHttpContext();  
        //在本地上下问中绑定一个本地存储  
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);  
        
        try {
            
            HttpResponse httpResponse = SingletonClient.getHttpClient().execute(post,localContext);
            String status="初始化失败";    
            if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY )            {                
                status="初始化成功";                
            }
            // Do not feel like reading the response body
            
// Call abort on the request object
            post.abort();
            System.out.println(status);
             
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return localContext;
        
    }
    

优化建议:

其实现在抢书已经拼到了毫秒级,单靠这种单用户一次性提交抢到书的几率还是不大的

 

 所以建议修改程序,增加几个HttpContext实例(多用户,我借用了朋友一个帐号),在main函数里面,执行几个 SingletonClient.getHttpClient().execute(post2,localContext);方法

SingletonClient.getHttpClient().execute(post2,localContext1);

SingletonClient.getHttpClient().execute(post2,localContext2);

SingletonClient.getHttpClient().execute(post2,localContext3);

…… 

 

 

 

 

posted on 2012-10-25 12:59  刺猬的温驯  阅读(1335)  评论(0编辑  收藏  举报