• HttpClient的代码封装,便于直接调用


    import java.io.IOException;

    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    import java.util.Map.Entry;

    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.HttpException;
    import org.apache.commons.httpclient.NameValuePair;
    import org.apache.commons.httpclient.methods.PostMethod;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;

    import com.ivms6.core.util.CollectionUtils;

    /**
    * HTTP请求工具类,通过httpclient发送请求
    *
    */
    public class HttpClientUtil {

    private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

    private final static int TIMEOUT_DEFAULT = 5000;

    /**
    * 发送post请求
    *
    * @param parameters
    * 参数
    * @return 返回值
    * @throws IOException
    * @throws HttpException
    */
    public static String post(String url, Map<String, String> parameters) throws HttpException, IOException {
    return post(url, parameters, TIMEOUT_DEFAULT); // 默认为5秒
    }
    /**
    * 发送post请求
    *
    * @param parameters
    * 参数
    * @return 返回值
    * @throws IOException
    * @throws HttpException
    */
    public static String post(String url, Map<String, String> parameters, int timeout) throws HttpException, IOException {
    if(logger.isDebugEnabled()){
    logger.debug("Create http post to server [{}].", url);
    }
    HttpClient httpclient = new HttpClient();
    // 设置超时
    httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);
    httpclient.getHttpConnectionManager().getParams().setSoTimeout(timeout);
    String body = invoke(httpclient, url, parameters);

    logger.info("Send http post to [{}] complate.", url);
    return body;
    }

    /**
    * 执行http请求
    * @param httpclient
    * @param httppost
    * @return
    * @throws IOException
    * @throws HttpException
    */
    private static String invoke(HttpClient httpclient, String url, Map<String, String> parameters) throws HttpException, IOException {
    PostMethod httppost = getPost(url, parameters);
    try {
    int sendStatus = httpclient.executeMethod(httppost);
    logger.info("Send httppost to server, status is [{}].", sendStatus);
    String body = httppost.getResponseBodyAsString();
    if (logger.isDebugEnabled()) {
    logger.debug("Get response from server success, response body is [{}].", body);
    }
    return body;
    } finally {
    // 释放资源
    httppost.releaseConnection();
    }
    }

    /**
    * 生成http post请求对象
    * @param url
    * @param params
    * @return
    */
    private static PostMethod getPost(String url, Map<String, String> params) {
    PostMethod postmethod = new PostMethod(url);
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    if(!CollectionUtils.isEmpty(params)){
    for (Entry<String, String> entry : params.entrySet()) {
    if(logger.isDebugEnabled()){
    logger.debug("Post parameter [{} = {}].", new Object[]{entry.getKey(), entry.getValue()});
    }
    nvps.add(new NameValuePair(entry.getKey(), entry.getValue()));
    }
    }else{
    if(logger.isDebugEnabled()){
    logger.debug("Post parameter is empty.");
    }
    }
    NameValuePair[] nvpArray = nvps.toArray(new NameValuePair[nvps.size()]);
    postmethod.addParameters(nvpArray);
    return postmethod;
    }

    /**
    * http 以put方式发送数据
    * @param url
    * @param jsonParam
    * @return
    * @throws ClientProtocolException
    * @throws IOException
    */
    public static String doPut(String url,String jsonParam) throws ClientProtocolException, IOException{
    DefaultHttpClient httpClient = new DefaultHttpClient();
    StringBuilder result = new StringBuilder();
    HttpPut request=new HttpPut(url);
    request.addHeader("Content-Type", "application/json;charset=UTF-8");
    request.addHeader("Accept", "application/json");
    StringEntity input=null;
    try{
    input=new StringEntity(jsonParam);
    }catch (UnsupportedEncodingException e ) {
    e.printStackTrace();
    }
    request.setEntity(input);
    HttpResponse response = httpClient.execute(request);
    logger.info("Response is :"+response);
    if (response.getStatusLine().getStatusCode() != 200) {
    throw new RuntimeException("Failed : HTTP error code : "
    + response.getStatusLine().getStatusCode());
    }
    BufferedReader br = new BufferedReader(new InputStreamReader(
    (response.getEntity().getContent())));
    String output=null;
    while ((output = br.readLine()) != null) {
    result.append(output);
    }
    return result.toString();
    }


    }

  • 相关阅读:
    saxbuilder用法
    【转】开篇python--明白python文件如何组织,理解建立源文件
    [转]linux awk命令详解
    sed 指定行范围匹配(转)
    MySQL Error Code文档手册---摘自MySQL官方网站
    java文件读写操作大全
    详解coredump
    Java中Map根据键值(key)或者值(value)进行排序实现
    java如何对map进行排序详解(map集合的使用)
    遍历Map的四种方法
  • 原文地址:https://www.cnblogs.com/xxj-bigshow/p/7573897.html
Copyright © 2020-2023  润新知