`
JLK
  • 浏览: 236717 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

httpclient 解析 dwr

阅读更多

用的是htppclient 4.0访问DWR时发生。 
throw 'allowScriptTagRemoting is false.'; 
//#DWR-REPLY 
if (window.dwr) dwr.engine._remoteHandleBatchException({ name:'org.directwebremoting.extend.ServerException', message:'The specified call count is not a number' }); 
else if (window.parent.dwr) window.parent.dwr.engine._remoteHandleBatchException({ name:'org.directwebremoting.extend.ServerException', message:'The specified call count is not a number' }); 


代码如下: 

import java.io.InputStream;   
import java.util.ArrayList;   
import java.util.HashMap;   
import java.util.List;   
import java.util.Map;   
import java.util.Set;   
import java.util.regex.Matcher;   
import java.util.regex.Pattern;   
  
import org.apache.http.Header;   
import org.apache.http.HttpEntity;   
import org.apache.http.HttpResponse;   
import org.apache.http.HttpVersion;   
import org.apache.http.NameValuePair;   
import org.apache.http.client.CookieStore;   
import org.apache.http.client.entity.UrlEncodedFormEntity;   
import org.apache.http.client.methods.HttpPost;   
import org.apache.http.conn.ClientConnectionManager;   
import org.apache.http.conn.params.ConnManagerParams;   
import org.apache.http.conn.scheme.PlainSocketFactory;   
import org.apache.http.conn.scheme.Scheme;   
import org.apache.http.conn.scheme.SchemeRegistry;   
import org.apache.http.cookie.Cookie;   
import org.apache.http.impl.client.DefaultHttpClient;   
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;   
import org.apache.http.impl.cookie.BasicClientCookie;   
import org.apache.http.message.BasicHeader;   
import org.apache.http.message.BasicNameValuePair;   
import org.apache.http.params.BasicHttpParams;   
import org.apache.http.params.HttpParams;   
import org.apache.http.params.HttpProtocolParams;   
import org.apache.http.protocol.HTTP;   
   
public class DwrTest {   
private DefaultHttpClient httpclient;   
       
    private Header[] headers = {new BasicHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; " +   
            "Windows NT 5.1; SV1; .NET CLR 2.0.50727; CIBA)"),    
            new BasicHeader("Accept-Language", "zh-cn"),    
            new BasicHeader("Accept", " image/gif, image/x-xbitmap, image/jpeg, " +   
                    "image/pjpeg, application/x-silverlight, application/vnd.ms-excel, " +   
                    "application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */*"),    
            new BasicHeader("Content-Type", "application/x-www-form-urlencoded"),    
            new BasicHeader("Accept-Encoding", "gzip, deflate")};   
       
    private Cookie cookie;   
       
    /**   
     * 登录请求的地址   
     */   
    private String action;   
       
    /**  
     * 用户名  
     */  
    private String username;   
       
    /**  
     * 密码  
     */  
    private String password;   
       
    /**  
     * 请求的其他参数  
     */  
    private Map<String, String> map = new HashMap<String, String>();   
       
    public static void main(String[] args) throws Exception {   
        String action = "http://localhost:8080/dwrDemo/index.jsp";   
       // String username = "admin";   
        //String password = "admin";   
        Map<String, String> map = new HashMap<String, String>();   
        //map.put("yourName", username);   
        //map.put("&j_password", password);   
           
        DwrTest dwrTest = new DwrTest();   
        dwrTest.setAction(action);   
       // dwrTest.setMap(map);   
        String html = dwrTest.login();  // 登录   
        System.out.println(html);   
           
        action = "http://localhost:8080/dwrDemo/js/engine.js";   
        map.clear();   
        dwrTest.setAction(action);   
        html = dwrTest.execute();   
       // System.out.println(html);   
        String regEx = "dwr\\.engine\\._origScriptSessionId = \"(\\w+)\"";   
        String scriptSessionId = null;   
        Pattern p = Pattern.compile(regEx);   
        Matcher m = p.matcher(html);   
        while (m.find()) {   
            scriptSessionId = m.group(1);   
        }   
          System.out.println(scriptSessionId); 
        DefaultHttpClient httpClient = dwrTest.getHttpclient();   
        CookieStore cookes = httpClient.getCookieStore();   
        List<Cookie> list = cookes.getCookies();   
        System.out.println(list.size()+"CCCCCCCCC"); 
        String httpSessionId = "";   
        for (Cookie cookie : list) {   
            String cookieName = cookie.getName();  
            //System.out.println(cookieName+"=========="); 
            if ("JSESSIONID".equals(cookieName)) {   
                httpSessionId = cookie.getValue();   
                System.out.println(httpSessionId); 
            }   
        }   
           
        Header[] headers = {new BasicHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; " +   
        "Windows NT 5.1; SV1; .NET CLR 2.0.50727; CIBA)"),    
        new BasicHeader("Accept-Language", "zh-cn"),   
        new BasicHeader("Content-Type", "text/plain"), 
        new BasicHeader("X_REQUESTED_WITH", "XMLHttpRequest"), 
        new BasicHeader("Accept-Encoding", "gzip, deflate")}; 
        //new BasicHeader("X_REQUESTED_WITH", "XMLHttpRequest"); 
        action = "http://localhost:8080/dwrDemo/dwr/call/plaincall/service.HelloWorld.dwr";   
        map.clear();   
        map.put("model", "CNPC_GWLIST");   
        map.put("httpSessionId", httpSessionId);   
        map.put("scriptSessionId", scriptSessionId);   
        map.put("c0-scriptName", "Service");   
        map.put("c0-methodName", "HelloWorld");   
        map.put("&c0-id", "0");   
        map.put("&c0-param0", "string:gwtype%3D'fw'");   
        map.put("&c0-param1", "string:");   
        map.put("&c0-param2", "string:admin");   
        map.put("&c0-param3", "number:0");   
        map.put("&c0-param4", "string:15");   
        map.put("&c0-param5", "string:SENDTIME%20DESC");   
        map.put("&batchId", "0");   
        dwrTest.setAction(action);   
        dwrTest.setMap(map);   
        dwrTest.setHeaders(headers);   
        html = dwrTest.execute();   

        System.out.println(html);   
    }   
       
    /**  
     * 初始化  
     */  
    public DwrTest() {   
        HttpParams params = new BasicHttpParams();   
        ConnManagerParams.setMaxTotalConnections(params, 100);   
        ConnManagerParams.setTimeout(params, 1000);   
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);   
        // HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_0);   
        SchemeRegistry schemeRegistry = new SchemeRegistry();   
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));   
        ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);   
           
        httpclient = new DefaultHttpClient(cm, params);   
        httpclient = new DefaultHttpClient();   
    }   
       
    /**  
     * 初始化  
     *   
     * @param action  
     * @param username  
     * @param passwork  
     * @param map  
     */  
    public DwrTest(String action,    
            String username, String passwork, Map<String, String> map) {   
  
        HttpParams params = new BasicHttpParams();   
        ConnManagerParams.setMaxTotalConnections(params, 100);   
        ConnManagerParams.setTimeout(params, 10000);   
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);   
        // HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_0);   
        SchemeRegistry schemeRegistry = new SchemeRegistry();   
        schemeRegistry.register(   
                new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));   
        ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);   
           
        httpclient = new DefaultHttpClient(cm, params);   
//      httpclient = new DefaultHttpClient();   
        this.action = action;   
        this.username = username;   
        this.password = passwork;   
        if (map == null) {   
            map = new HashMap<String, String>();   
        }   
        this.map = map;   
    }   
       
    /**  
     * 初始化  
     *   
     * @param httpclient  
     */  
    public DwrTest(DefaultHttpClient httpclient) {   
        this.httpclient = httpclient;   
    }   
       
    /**  
     * 初始化  
     *   
     * @param httpclient  
     * @param username  
     * @param passwork  
     */  
    public DwrTest(DefaultHttpClient httpclient, String action,    
            String username, String passwork, Map<String, String> map) {   
        this.httpclient = httpclient;   
        this.action = action;   
        this.username = username;   
        this.password = passwork;   
        if (map == null) {   
            map = new HashMap<String, String>();   
        }   
        this.map = map;   
    }   
       
    /**  
     * 登录  
     *   
     * @param httpclient  
     * @return  
     * @throws Exception  
     */  
    public String login() throws Exception {   
        HttpPost httpost = new HttpPost(action);  // 初始化Post   
  
        List <NameValuePair> nvps = new ArrayList <NameValuePair>();  // 构建参数   
        nvps.add(new BasicNameValuePair("yourName", username));   
       // nvps.add(new BasicNameValuePair("password", password));   
        // 增加其他的参数   
        Set<String> set = map.keySet();   
        for (String string : set) {   
            nvps.add(new BasicNameValuePair(string, map.get(string)));   
        }   
           
        httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));   
        httpost.setHeaders(headers);   
           
        HttpResponse response = httpclient.execute(httpost);  // 运行action   
        HttpEntity entity = response.getEntity();   // 获得实体   
  
        InputStream in = entity.getContent();  // 获得实体的内容   
        StringBuffer   out   =   new   StringBuffer();   
        byte[] b = new byte[4096];   
        for(int n; (n = in.read(b)) != -1;) {   
            out.append(new   String(b, 0, n));   
        }   
  
        if (entity != null) {   
            entity.consumeContent();   
        }   
           
//      取出页面上返回的LtpaToken Cookie值。   
        String html = out.toString();   
        String regEx = "(\"LtpaToken=(.+)\")";   
        String ltpaToken = null;   
        Pattern p = Pattern.compile(regEx);   
        Matcher m = p.matcher(html);   
        while (m.find()) {   
            ltpaToken = m.group(1);   
            if (ltpaToken.length() > 11) {   
                ltpaToken = ltpaToken.substring(11);   
                ltpaToken = ltpaToken.substring(0, ltpaToken.lastIndexOf("\""));   
            }   
        }   
        BasicClientCookie cookie = new BasicClientCookie("LtpaToken", ltpaToken);   
        cookie.setDomain(".tj.unicom.local");   
        cookie.setPath("/");   
        CookieStore cookies = httpclient.getCookieStore();   
        cookies.addCookie(cookie);   
        httpclient.setCookieStore(cookies);   
           
        return html;   
    }   
       
    public String execute() throws Exception {   
        HttpPost httpost = new HttpPost(action);  // 初始化Post   
  
        List <NameValuePair> nvps = new ArrayList <NameValuePair>();  // 构建参数   
        // 增加其他的参数   
        Set<String> set = map.keySet();   
        for (String string : set) {   
            nvps.add(new BasicNameValuePair(string, map.get(string)));   
        }   
           
        httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));   
        httpost.setHeaders(headers);   
           
        HttpResponse response = httpclient.execute(httpost);  // 运行action   
        HttpEntity entity = response.getEntity();   // 获得实体   
  
        InputStream in = entity.getContent();  // 获得实体的内容   
        StringBuffer   out   =   new   StringBuffer();   
        byte[] b = new byte[4096];   
        for(int n; (n = in.read(b)) != -1;) {   
            out.append(new   String(b, 0, n));   
        }   
  
        if (entity != null) {   
            entity.consumeContent();   
        }   
           
        String html = out.toString();   
        return html;   
    }   
       
    @SuppressWarnings("unused")   
    private void print(InputStream in) throws Exception {   
        StringBuffer   out   =   new   StringBuffer();   
        byte[] b = new byte[4096];   
        for(int n; (n = in.read(b)) != -1;) {   
            out.append(new   String(b, 0, n));   
        }   
        System.out.println("-------------------------------------------");   
        System.out.println(out.toString());   
        System.out.println("-------------------------------------------");   
           
    }   
       
    @SuppressWarnings("unused")   
    private String toStr(InputStream in) throws Exception {   
        StringBuffer   out   =   new   StringBuffer();   
        byte[] b = new byte[4096];   
        for(int n; (n = in.read(b)) != -1;) {   
            out.append(new   String(b, 0, n));   
        }   
        String str = out.toString();   
        return str;   
    }   
  
    public String getAction() {   
        return action;   
    }   
  
    public String getUsername() {   
        return username;   
    }   
  
    public String getPassword() {   
        return password;   
    }   
       
    public Map<String, String> getMap() {   
        return map;   
    }   
  
    public void setAction(String action) {   
        this.action = action;   
    }   
  
    public void setUsername(String username) {   
        this.username = username;   
    }   
  
    public void setPassword(String password) {   
        this.password = password;   
    }   
       
    public void setMap(Map<String, String> map) {   
        this.map = map;   
    }   
  
    public DefaultHttpClient getHttpclient() {   
        return httpclient;   
    }   
  
    public Cookie getCookie() {   
        return cookie;   
    }   
  
    public void setHttpclient(DefaultHttpClient httpclient) {   
        this.httpclient = httpclient;   
    }   
  
    public void setCookie(Cookie cookie) {   
        this.cookie = cookie;   
    }   
       
    public void setHeaders(Header[] headers) {   
        this.headers = headers;   
    }   
       
    public Header[] getHeaders() {   
        return headers;   
    }   
}  
 
分享到:
评论
2 楼 feilian09 2014-09-04  
怎么解决的!
1 楼 llscp 2013-03-31  
楼主怎么解决的/

相关推荐

    java-HttpClient学习,和解析html.zip

    java_HttpClient学习,和解析htmljava_HttpClient学习,和解析html java_HttpClient学习,和解析htmljava_HttpClient学习,和解析html java_HttpClient学习,和解析htmljava_HttpClient学习,和解析html java_...

    httpClient采集jsoup解析

    HttpClient和Jsoup是Java开发中常用的两个库,用于网络数据采集和HTML解析。HttpClient提供了强大的HTTP客户端服务,而Jsoup则是一个优秀的库,用于处理和理解HTML文档结构。本篇文章将深入探讨这两个库的使用方法...

    使用httpClient组件解析html并解决字符编码

    使用HttpClient组件解析HTML并解决字符编码问题 在网络信息采集中,经常需要解析HTML页面以获取有用的信息。使用HttpClient组件可以轻松地实现这一任务。但是,在实际使用中,经常会遇到字符集编码乱码问题。本文将...

    Android HttpClient与Json解析

    在本示例中,HttpClient被用来从服务器获取数据,这些数据通常是JSON格式,这是一种轻量级的数据交换格式,易于人阅读和编写,同时也方便机器解析和生成。 首先,我们需要了解如何使用Android的HttpClient。在...

    利用HttpClient获取数据并用Gson解析Json数据

    本教程将专注于使用Apache HttpClient库获取网络数据,然后使用Google的Gson库解析JSON格式的数据。这是一个基础但重要的技能,对于任何想要与服务器进行交互的开发者来说都是必备的。 首先,我们需要了解`...

    HttpClientHelper 工具类

    - **XML**:如果服务器返回XML格式的数据,HttpClientHelper可以提供相应的解析方法,将XML转换为C#对象。 4. **单例模式实现**: - `SingleHelper` 类通常包含一个静态成员变量来保存HttpClientHelper的实例,并...

    httpclient.jar包下载

    《深入解析httpclient.jar及其与code.jar的关联》 在Java开发中,HTTP通信是不可或缺的一部分,而Apache HttpClient库正是Java实现HTTP客户端操作的重要工具。本文将深入探讨httpclient.jar包,以及它与code.jar包...

    commons-httpclient-3.1jar包

    4. Cookie管理:通过CookiePolicy和CookieSpec接口,实现对服务器返回的Cookie进行解析、存储和回发。 5. 连接管理:HttpClient 3.1引入了ConnectionManager接口,用于管理HTTP连接,包括连接的创建、复用和关闭。 ...

    Apache httpclient源码4.5.12

    通过创建HttpClient实例,你可以构建请求,并配置各种设置,如超时、重试策略和连接池。`HttpHost`类代表HTTP服务器的地址和端口,而`HttpRequest`和`HttpResponse`分别表示HTTP请求和响应对象。 `HttpGet`, `...

    httpclient-4.5.5-API文档-中文版.zip

    赠送jar包:httpclient-4.5.5.jar; 赠送原API文档:httpclient-4.5.5-javadoc.jar; 赠送源代码:httpclient-4.5.5-sources.jar; 包含翻译后的API文档:httpclient-4.5.5-javadoc-API文档-中文(简体)版.zip ...

    HttpClientUtil工具类 里面包含GET POST 及返回值处理

    - **处理返回值**:获取到的返回值通常是一个字符串,开发者可以根据业务需求解析这个字符串,如JSON解析、XML解析等。 4. **注意点**: - **连接管理**:为了防止过多的并发连接导致资源耗尽,HttpClientUtil...

    commons-httpclient-3.0.jar JAVA中使用HttpClient可以用到

    本文将深入解析`commons-httpclient-3.0.jar`,它是HttpClient的一个重要版本,为开发者提供了强大而灵活的HTTP客户端功能。 HttpClient是一个开放源代码的JAVA库,它允许开发人员执行HTTP和HTTPS协议的请求。`...

    httpClient需要的jar包

    EntityUtils类提供了读取和解析响应实体内容的方法。 5. **重试和恢复策略**:HttpClient可以通过设置RetryHandler来决定在网络异常或HTTP错误状态时是否重试请求。 6. **认证和安全**:HttpClient支持多种认证...

    HttpClient 调用WebService示例

    在本文中,我们将深入探讨如何使用HttpClient调用WebService。 首先,调用WebService通常涉及SOAP(Simple Object Access Protocol)或RESTful API。HttpClient可以处理这两种类型的Web服务。在本示例中,我们假设...

    Java HttpClient 全部的jar包

    10. `xercesImpl-2.11.0.jar`: Xerces是XML解析器,用于解析和验证XML文档。同样,当HttpClient处理XML格式的HTTP响应时,它可能会发挥作用。 11. `xml-apis-1.4.01.jar`: XML APIs库提供了对XML标准的接口,包括...

    httpclient-4.5.jar

    2. **HttpCore**:HttpCore是HttpClient的基础模块,提供网络I/O处理和HTTP协议解析。它的主要任务是建立和维护TCP连接,以及解析HTTP消息头和体。 3. **RequestExecutor**:这是处理请求和响应的接口,HttpClient...

    HttpClient所需jar包(全) httpClient.4.13jar

    在导入这些库后,可以通过创建HttpClient实例,设置请求参数,然后执行请求,最后解析响应来完成HTTP操作。例如,创建一个GET请求并获取响应体可以这样实现: ```java CloseableHttpClient httpClient = ...

    ETL KETTLE 中利用Httpclient 调用webservice接口获取XML数据,并解析XML 数据

    ETL KETTLE 中利用Httpclient 调用webservice接口获取XML数据,并解析XML 数据。 完整的KTR实例

    httpclient httpclient.jar

    在本文中,我们将深入探讨HttpClient的核心概念、使用方法以及如何通过`httpclient.jar`进行实战应用。 首先,HttpClient的主要组件包括: 1. **HttpClient实例**:这是整个HTTP通信的核心,负责管理连接、请求和...

    HttpClient 3.x to HttpComponents HttpClient 4.x

    例如,在HttpClient 3.x中,代码可能会使用`***mons.httpclient.HttpClient`类和`***mons.httpclient.methods.GetMethod`等,而在4.x版本中,这些都被新的API所替代。程序员需要熟悉`org.apache....

Global site tag (gtag.js) - Google Analytics