• 大小: 5KB
    文件类型: .java
    金币: 1
    下载: 0 次
    发布日期: 2021-06-15
  • 语言: Java
  • 标签: http  

资源简介

java http工具,包括get、post、json格式请求,使用httpclient

资源截图

代码片段和文件信息

package com.xgdmsr.common.utils;

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.logging.Log;
import org.apache.commons.logging.LogFactory;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * http工具类
 */
public class HttpUtil {
    private static final Log logger = LogFactory.getLog(HttpUtil.class);
    private static String ENCOCE_UTF_8 = “UTF-8“;
    private static CloseableHttpClient client = null;

    private HttpUtil() {
    }

    private static CloseableHttpClient getClientInstance() {
        if (client == null) {
            synchronized (HttpUtil.class) {
                if (client == null) {
                    // 设置每个路由的最大并发连接数为20以提高性能,默认为2
                    client = HttpClientBuilder.create().setMaxConnPerRoute(20)
                            .build();
                }
            }
        }
        return client;
    }


    /**
     * @param url
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String httpGet(String url) throws ClientProtocolException IOException {
        // 创建httpget
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = getClientInstance().execute(httpGet);
        HttpEntity entity = response.getEntity();
        return EntityUtils.toString(entity);
    }

    public static HttpEntity httpGetForEntity(String url) throws Exception {
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = getClientInstance().execute(httpGet);
        return response.getEntity();
    }

    /**
     * post请求
     *
     * @param url
     * @param params
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String httpPost(String url Map params) throws 

评论

共有 条评论