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

http代替ajax获取数据

阅读更多
/**
*
*/
package com.certus.util.httpClient;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.UUID;

import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.log4j.Logger;

import com.certus.util.CommonUtil;

/**
* @description 通过HttpClient Post请求服务器数据的Request
* @author renjing
* @time 2015年2月10日上午10:15:37
*/
public class HttpClientPostRequest extends AbstractHttpClientRequest {

    private Logger logger = Logger.getLogger(HttpClientPostRequest.class);

    public HttpClientPostRequest(String url) {
        super(url);
    }

    /*@Override
    public HttpMethod getHttpMethod() {
    NameValuePair[] pairs = new NameValuePair[this.params.size()];
    NameValuePair pair = null;
    String contentType = "multipart/form-data";
    int i = 0;
    for (Entry<String, Object> entry : params.entrySet()) {
    pair = new NameValuePair(entry.getKey(), String.valueOf(entry
    .getValue()));
    pairs[i++] = pair;
    }
    PostMethod httpMethod = new PostMethod(this.url);
    httpMethod.setRequestBody(pairs);

    if (StringUtils.isNotEmpty(contentType))
    httpMethod.setRequestHeader("Content-Type", contentType);

    return httpMethod;
    }*/

    @Override
    public HttpMethod getHttpMethod() {
        /*      NameValuePair[] pairs = new NameValuePair[this.params.size()];
              NameValuePair pair = null;
              String contentType = "";
              int i = 0;
              for (Entry<String, Object> entry : params.entrySet()) {
                  pair = new NameValuePair(entry.getKey(), String.valueOf(entry.getValue()));
                  pairs[i++] = pair;
              }

              PostMethod httpMethod = new PostMethod(this.url);
              httpMethod.setRequestBody(pairs);

              if (StringUtils.isNotEmpty(contentType))
                  httpMethod.setRequestHeader("Content-Type", contentType);

              return httpMethod;*/
        return null;
    }

    public String processPost(InputStream input, String tempName, String userId, String token) throws HttpClientException {
        String result = httpSendPIC(url, tempName, file2byte(input), userId, token);
        return result;
    }

    /**
     *
     * @Title    函数名称: processPostEntity
     * @Description   功能描述: 创建实例 需要post一个 entity的json(String)格式
     * @param    参          数:
     * @return          返  回   值: String 
     * @throws
     */
    @SuppressWarnings({ "resource", "deprecation" })
    public String processPostEntity(String entityJson) {
        String token = CommonUtil.getAuthToken();
        StringBuffer result = new StringBuffer();
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost method = new HttpPost(url);
        if (method != null) {
            try {
                // 添加参数
                method.setEntity(new StringEntity(entityJson, HTTP.UTF_8));
                method.setHeader("X-Auth-Token", token);
                method.setHeader("Content-Type", "application/Json");
                // 设置编码
                HttpResponse response = httpClient.execute(method);
                InputStream in = response.getEntity().getContent();
                BufferedReader breader = new BufferedReader(new InputStreamReader(in, "utf-8"));
                String st = breader.readLine();
                result.append(st);
                while (st != null) {
                    st = breader.readLine();
                }
                int statusCode = response.getStatusLine().getStatusCode();
                logger.info("statusCode:" + statusCode);
            } catch (IOException e) {
                // 发生网络异常
                logger.error("exception occurred!\n" + ExceptionUtils.getFullStackTrace(e));
            } finally {
                method.abort();
            }
        }
        return result.toString();
    }

    /**
     *
     * @Title           函数名称:   processPostEntity
     * @Description     功能描述:   创建实例 需要post一个 entity的json(String)格式
     * @param           参          数:  
     * @return          返  回   值:   String 
     * @throws
     */
    @SuppressWarnings({ "resource", "deprecation" })
    public String processPostEntity(String entityJson, boolean isPostInfo) {
        String token = CommonUtil.getAuthToken();
        StringBuffer result = new StringBuffer();
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost method = new HttpPost(url);
        if (method != null) {
            try {
                // 添加参数
                method.setEntity(new StringEntity(entityJson, HTTP.UTF_8));
                method.setHeader("X-Auth-Token", token);
                // 记录日志需要的参数
                if (isPostInfo) {
                    method.setHeader("Event-Id", UUID.randomUUID().toString());
                    method.setHeader("User-Id", CommonUtil.getUserId());
                }
                method.setHeader("Content-Type", "application/Json");
                // 设置编码
                HttpResponse response = httpClient.execute(method);
                InputStream in = response.getEntity().getContent();
                BufferedReader breader = new BufferedReader(new InputStreamReader(in, "utf-8"));
                String st = breader.readLine();
                result.append(st);
                while (st != null) {
                    st = breader.readLine();
                }
                int statusCode = response.getStatusLine().getStatusCode();
                logger.info("statusCode:" + statusCode);
            } catch (IOException e) {
                // 发生网络异常
                logger.error("exception occurred!\n" + ExceptionUtils.getFullStackTrace(e));
            } finally {
                method.abort();
            }
        }
        return result.toString();
    }

    @SuppressWarnings({ "resource", "deprecation" })
    public String processPostParam() {
        String token = CommonUtil.getAuthToken();
        StringBuffer result = new StringBuffer();
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost method = new HttpPost(url);
        if (method != null) {
            try {
                method.setHeader("X-Auth-Token", token);
                method.setHeader("Content-Type", "text/plain");
                // 设置编码
                HttpResponse response = httpClient.execute(method);
                InputStream in = response.getEntity().getContent();
                BufferedReader breader = new BufferedReader(new InputStreamReader(in, "utf-8"));
                String st = breader.readLine();
                result.append(st);
                while (st != null) {
                    st = breader.readLine();
                }
                int statusCode = response.getStatusLine().getStatusCode();
                logger.info("statusCode:" + statusCode);
            } catch (IOException e) {
                // 发生网络异常
                logger.error("exception occurred!\n" + ExceptionUtils.getFullStackTrace(e));
            } finally {
                method.abort();
            }
        }
        return result.toString();
    }

    public String httpSendPIC(String url, String tplName, byte[] PostData, String userId, String token) {

        StringBuffer result = new StringBuffer();
        URL u = null;
        HttpURLConnection con = null;
        // 尝试发送请求
        try {
            u = new URL(url + "?nsdName=" + URLEncoder.encode(tplName, "UTF-8"));
            u = new URL(url + "?nsdName=" + tplName);
            // u = new URL(url);
            con = (HttpURLConnection) u.openConnection();
            con.setRequestMethod("POST");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setRequestProperty("Content-Type", "multipart/form-data");
            con.setRequestProperty("X-Auth-Token", token);
            con.setRequestProperty("Event-Id", UUID.randomUUID().toString());
            con.setRequestProperty("User-Id", userId);

            con.setConnectTimeout(20000);
            con.setReadTimeout(300000);
            OutputStream outStream = con.getOutputStream();
            outStream.write(PostData);
            outStream.flush();
            outStream.close();
            System.out.println(con.getResponseCode());
            System.out.println(con.getResponseMessage());

            // 读取返回内容
            try {
                InputStream in = con.getInputStream();
                BufferedReader breader = new BufferedReader(new InputStreamReader(in, "utf-8"));
                String st = breader.readLine();
                result.append(st);
                while (st != null) {
                    st = breader.readLine();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }
        System.out.println(result.toString());
        return result.toString();
    }

    public byte[] file2byte(InputStream input) {
        byte[] data = null;
        try {
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int numBytesRead = 0;
            while ((numBytesRead = input.read(buf)) != -1) {
                output.write(buf, 0, numBytesRead);
            }
            data = output.toByteArray();
            output.close();
            input.close();
        } catch (FileNotFoundException ex1) {
            ex1.printStackTrace();
        } catch (IOException ex1) {
            ex1.printStackTrace();
        }
        return data;
    }
}
========================================================



package com.certus.util.httpClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.certus.util.CommonUtil;

/**
* @description 抽象HttpClient 请求web服务器的request
* @author renjing
* @time 2015年2月10日上午10:15:37
*/
public abstract class AbstractHttpClientRequest implements HttpClientRequest {

    private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(AbstractHttpClientRequest.class);

    // 请求URL地址
    protected String url;
    // 请求参数
    protected Map<String, Object> params;

    /**
     * Constructor Method With All Params
     * @param url 请求URL
     */
    public AbstractHttpClientRequest(String url) {
        if (StringUtils.isEmpty(url))
            throw new NullPointerException("Cannot constract a HttpClientRequest with empty url.");

        this.url = url;
        this.params = new HashMap<String, Object>();
    }

    /**
     * 添加request参数
     * @param name 参数名
     * @param value 参数值
     */
    public void addParam(String name, Object value) {
        this.params.put(name, value);
    }

    /**
     * 执行请求
     * @throws HttpClientException httpClient请求异常
     */
    @Override
    public int process(HttpClientResponseHandler httpClientResponseHandler) throws HttpClientException {
        String auth_token = null;
        try {
            auth_token = CommonUtil.getAuthToken();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 获取子类的具体的HttpMethod实现
        HttpMethod httpMethod = this.getHttpMethod();
        // Head 里面塞值 -- modify by renjing
        // --- X-Auth-Token 值取什么?
        logger.info("client auth_token=" + auth_token);
        Header header = new Header("X-Auth-Token", auth_token);
        httpMethod.setRequestHeader(header);
        if (ObjectUtils.isNull(httpMethod))
            throw new NullPointerException("Cannot process request because the httpMethod is null.");

        HttpClient httpClient = new HttpClient();
        httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");

        try {
            long start = System.currentTimeMillis();
            logger.info("Begin to visit {}.", httpMethod.getURI());
            httpClient.executeMethod(httpMethod);
            logger.info("End to visit and take: {} ms.", (System.currentTimeMillis() - start));
        } catch (IOException e) {
            throw new HttpClientException(httpMethod.getPath(), e.getMessage());
        }

        // 利用HttpClientResponseHandler处理响应结果
        String retCode = null;
        String msg = null;
        if (ObjectUtils.isNotNull(httpClientResponseHandler))
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(httpMethod.getResponseBodyAsStream()));
                StringBuilder builder = new StringBuilder();
                String str = null;
                while ((str = reader.readLine()) != null) {
                    builder.append(str);
                }
                String response = builder.toString();
                // httpClientResponseHandler.handle(response);
                JSONObject jsonObj = JSONObject.parseObject(response);// .fromObject(response);
                retCode = jsonObj.getString("retCode");
                msg = jsonObj.getString("msg");
                httpClientResponseHandler.handle(response, retCode, msg);
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }

        httpMethod.releaseConnection();
        /* if (retCode == null || !retCode.equals("ok")) {
             throw new RuntimeException(msg);
         } else {
             return 0;
         }*/
        return 0;
    }

    /**
     * 执行请求
     * @throws HttpClientException httpClient请求异常   需要记录日志
     */
    @Override
    public int processAndSaveLog(HttpClientResponseHandler httpClientResponseHandler) throws HttpClientException {
        String auth_token = null;
        try {
            auth_token = CommonUtil.getAuthToken();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 获取子类的具体的HttpMethod实现
        HttpMethod httpMethod = this.getHttpMethod();
        // Head 里面塞值 -- modify by renjing
        // --- X-Auth-Token 值取什么?
        logger.info("client auth_token=" + auth_token);
        // Header header = new Header("X-Auth-Token", auth_token);
        httpMethod.addRequestHeader("X-Auth-Token", auth_token);

        httpMethod.addRequestHeader("Event-Id", UUID.randomUUID().toString());
        httpMethod.addRequestHeader("User-Id", CommonUtil.getUserId());
        if (ObjectUtils.isNull(httpMethod))
            throw new NullPointerException("Cannot process request because the httpMethod is null.");

        HttpClient httpClient = new HttpClient();
        httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");

        try {
            long start = System.currentTimeMillis();
            logger.info("Begin to visit {}.", httpMethod.getURI());
            httpClient.executeMethod(httpMethod);
            logger.info("End to visit and take: {} ms.", (System.currentTimeMillis() - start));
        } catch (IOException e) {
            throw new HttpClientException(httpMethod.getPath(), e.getMessage());
        }

        // 利用HttpClientResponseHandler处理响应结果
        String retCode = null;
        String msg = null;
        if (ObjectUtils.isNotNull(httpClientResponseHandler))
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(httpMethod.getResponseBodyAsStream()));
                StringBuilder builder = new StringBuilder();
                String str = null;
                while ((str = reader.readLine()) != null) {
                    builder.append(str);
                }
                String response = builder.toString();
                // httpClientResponseHandler.handle(response);
                JSONObject jsonObj = JSONObject.parseObject(response);// .fromObject(response);
                retCode = jsonObj.getString("retCode");
                msg = jsonObj.getString("msg");
                httpClientResponseHandler.handle(response, retCode, msg);
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }

        httpMethod.releaseConnection();
        /* if (retCode == null || !retCode.equals("ok")) {
             throw new RuntimeException(msg);
         } else {
             return 0;
         }*/
        return 0;
    }

    /**
     * 子类实现返回具体的HttpMethod对象
     * @return HttpMethod
     */
    public abstract HttpMethod getHttpMethod();
}
================================================================


/**
*
*/
package com.certus.util.httpClient;

/**
* @descriptionHttpClient 请求web服务器的request
* @author renjing
* @tiem 2015年2月10日上午10:15:37
*/
public interface HttpClientRequest {
    /**
    * 添加request参数
    * @param name 参数名
    * @param value 参数值
    */
    public void addParam(String name, Object value);

    /**
     * 执行request请求
     * @param httpClientResponseHandler 处理响应数据handler
     * @throws HttpClientException
     */
    public int process(HttpClientResponseHandler httpClientResponseHandler) throws HttpClientException;

    public int processAndSaveLog(HttpClientResponseHandler httpClientResponseHandler) throws HttpClientException;

}
=======================================
例子

String resultJson = JSONObject.toJSON(instance).toString();
        HttpClientPostRequest postRequest = new HttpClientPostRequest(ConfigFileLoad.getConfContent("NFVO_IP") + "/rest/nsrs/instantiate");

        String result = postRequest.processPostEntity(resultJson, true);
        JSONObject jsonObj = JSONObject.parseObject(result);
分享到:
评论

相关推荐

    AjaxRequest(Ajax使用包)

    3. **DOM (Document Object Model)**: 用于操作HTML或XML文档结构,Ajax获取的数据会通过DOM动态地更新页面元素。 4. **CSS**: 用于美化更新后的页面元素。 5. **JSON (JavaScript Object Notation)**: 代替XML作为...

    上传文件AJAX

    AJAX(Asynchronous JavaScript and XML)的核心是利用JavaScript进行异步通信,XML最初是用来传输数据的格式,但现在更多地使用JSON来代替。 ### AJAX文件上传原理 1. **创建XMLHttpRequest对象**:在所有现代...

    AJAX生成静态HTML

    在这个"toHtmlDemo"中,很可能是通过Struts的Action返回一个XML响应,前端JavaScript通过AJAX请求获取XML数据,然后解析并动态更新HTML内容。 XML是一种可扩展标记语言,用于存储和传输结构化数据。在AJAX中,XML常...

    ajax学习源码

    4. **处理返回数据**:通过responseText或responseXML属性获取服务器返回的数据,然后使用JavaScript动态更新页面。 **二、Ajax的应用场景** Ajax广泛应用于网页的局部刷新,如: 1. **表单提交**:用户填写表单...

    Ajax安全技术.pdf 高清扫描版

    - 使用HTTPS代替HTTP进行数据传输,保证数据传输的安全性和完整性; - 对于敏感信息的传输,还可以考虑使用额外的加密层。 3. **防止CSRF攻击** - 在表单中添加隐藏字段,用于存储随机生成的Token,并在服务器端...

    ajax 验证ppt

    7. **接收响应**:当状态变为4(完成)且状态码为200(成功)时,调用responseText或responseXML获取服务器返回的数据。 8. **处理数据**:使用JavaScript操作DOM,更新页面的相应部分。 **Ajax的局限性** 1. **...

    ajax测试使用实例,简单代码

    5. 接收响应:当状态变为4(完成),且status为200(成功)时,通过`responseText`或`responseXML`获取服务器返回的数据。 四、Ajax请求实例 以下是一个简单的Ajax GET请求示例: ```javascript var xhr = new ...

    AJAX-技术入门介绍.zip_ajax_异步请求

    2. 发起AJAX请求,获取下一页文章数据。 3. 解析返回的JSON数据。 4. 动态插入新的文章到页面中。 5. 更新分页信息。 ### 7. 注意事项 - 需要考虑浏览器兼容性,尤其是IE的老版本。 - 跨域问题需要妥善处理。 - ...

    ajax学习文档下载

    5. **接收响应**:当请求完成且状态为4(表示已完成)时,读取`responseText`或`responseXML`属性获取服务器返回的数据。 ### 2. JSON数据格式 JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,...

    ajax 、jsp实现的聊天室代码

    Ajax可以轻松实现长轮询,通过保持一个持续的HTTP连接,直到服务器有新数据可返回。 5. **安全性**:确保聊天室的安全性至关重要,可能涉及到防止跨站脚本攻击(XSS)、跨站请求伪造(CSRF)等。 6. **用户接口**...

    ASP+AJAX实现聊天室(无刷新)

    在"Chat2.0"这个项目中,开发者可能已经优化了用户界面,提高了性能,比如使用JSON格式代替XML传输数据,以减少数据量和提高处理速度。此外,可能还引入了错误处理机制,确保在网络不稳定或服务器响应慢时,仍能提供...

    ajax00009_async_trigger

    同步Ajax请求会阻塞浏览器,直到请求完成才会继续执行后续代码,这在某些需要确保数据获取完整后再进行其他操作的场景下可能有用。然而,通常推荐使用异步请求以保持页面的交互性。 在实际应用中,使用这样的自定义...

    PHP+Ajax网站开发典型实例(源码)

    4. **JSON数据格式**:在Ajax通信中,通常会使用JSON(JavaScript Object Notation)代替XML,因为JSON更轻量级且易于解析。你需要理解JSON的结构和PHP的json_encode与json_decode函数。 5. **用户界面更新**:通过...

    ajax经典实例大全

    5. **Ajax与Websocket**:对于需要实时双向通信的场景,可以考虑使用Websocket代替Ajax。 综上所述,"Ajax经典实例大全"涵盖了Ajax的基础概念、应用实例、与Java的结合,以及一些进阶话题。通过学习这些实例,...

    利用Google AJAX Search API

    使用这个API时,你需要创建一个自定义搜索引擎并获取其ID,然后在请求中使用这个ID代替API密钥。 7. **源码分析** 压缩包中的"Google 搜索引擎应用"可能包含示例代码或者一个完整的应用,你可以通过研究源码来深入...

    AJAX 入门培训PPT

    同时,AJAX技术不断发展,例如JSON代替XML成为更常见的数据交换格式,Fetch API逐渐替代XMLHttpRequest,提供更现代的异步请求解决方案。 总结来说,AJAX是构建富互联网应用的关键技术,它通过JavaScript和...

    ajax + div +js +xml+ servlet 实现无限级动态目录树(原创)

    在这个项目中,Servlet接收AJAX请求,根据请求参数查询数据库或其他数据源获取目录树数据,然后将数据封装成XML格式,返回给前端。Servlet还可以处理添加、删除、修改目录等操作,确保数据的一致性。 在实际应用中...

    AJAX课件及案例

    - **处理响应**:通过`responseText` 或 `responseXML` 属性获取服务器响应的数据,然后更新DOM。 **3. AJAX与JSON** - JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,同时也...

    Ajax的学习笔记

    这种技术的核心是JavaScript,XML最初是作为数据交换格式,但随着JSON的流行,现在更多地使用JSON代替XML。 ### 一、Ajax的基本工作原理 1. **创建XMLHttpRequest对象**:这是Ajax的核心组件,几乎所有的现代...

Global site tag (gtag.js) - Google Analytics