简单get/post方法http请求工具类,带head参数

版权声明:版权??? 版权.... 版权!!! 什么样的事要说三遍 https://blog.csdn.net/qq_16513911/article/details/82856365
package com.***.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import com.w3china.mingjing3.JsonResult;
import com.w3china.mingjing3.isp.Constants;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


public class HttpClientUtil {
    private static PoolingHttpClientConnectionManager cm;
    private static String UTF_8 = "UTF-8";

    private static void init() {
        if (cm == null) {
            cm = new PoolingHttpClientConnectionManager();
            cm.setMaxTotal(50);// 整个连接池最大连接数
            cm.setDefaultMaxPerRoute(5);// 每路由最大连接数,默认值是2
        }
    }
    /**
     * 通过连接池获取HttpClient
     */
    private static CloseableHttpClient getHttpClient() {
        init();
        return HttpClients.custom().setConnectionManager(cm).build();
    }

    private static ArrayList<NameValuePair> covertParams2NVPS(Map<String, Object> params) {
        ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
        for (Map.Entry<String, Object> param : params.entrySet()) {
            pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(param.getValue())));
        }

        return pairs;
    }
    //打印一下参数,并根据发送类型判断
    public static JsonResult<String> HttpRequest(String type,String url, Map<String, Object> paramMap) throws IOException, URISyntaxException {
        Map<String, Object> params = new HashMap<>();
        for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
            System.out.println(entry.getKey() + ":" + entry.getValue());
            params.put(entry.getKey(), entry.getValue());
        }
        if (type.equalsIgnoreCase("post")) {
            return postHttp(url, params);
        } else {
            return getHttp(url, params);
        }
    }
    //post请求
    public static JsonResult<String> postHttp(String url, Map<String, Object> params) throws IOException {
        HttpPost httpPost = new HttpPost(url);
        // 如果需要head信息的话
        // 多添一个参数 Map<String, Object> headers
        // for (Map.Entry<String, Object> param : headers.entrySet()) {
        //    httpPost.addHeader(param.getKey(), String.valueOf(param.getValue()));
        // }
        ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
        httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));
        CloseableHttpClient httpClient = getHttpClient();
        CloseableHttpResponse response = httpClient.execute(httpPost);
        return getHttpStatusOrEntity(response);
    }
    //get请求
    public static JsonResult<String> getHttp(String url, Map<String, Object> params) throws URISyntaxException, IOException {
        URIBuilder ub = new URIBuilder();
        ub.setPath(url);
        ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
        ub.setParameters(pairs);
        HttpGet httpGet = new HttpGet(ub.build());
        // 如果需要head信息
        // 多传 Map<String, Object> headers参数
        // for (Map.Entry<String, Object> param : headers.entrySet()) {
        //    httpGet.addHeader(param.getKey(), String.valueOf(param.getValue()));
        //}
        CloseableHttpClient httpClient = getHttpClient();
        CloseableHttpResponse response = httpClient.execute(httpGet);
        return getHttpStatusOrEntity(response);
    }
    //判断状态码是否成功   成功则返回数据
    public static JsonResult<String> getHttpStatusOrEntity( CloseableHttpResponse response) throws IOException {
        int statusCode = response.getStatusLine().getStatusCode();//状态码
        HttpEntity entity = response.getEntity();// 获取返回实体
        String  res= EntityUtils.toString(entity);
        response.close();
        switch (statusCode){
            case 200://:代表请求成功
                return JsonResult.ok(res);
            case 303://:代表重定向
                return JsonResult.error(303,res);
            case 400://:代表请求错误
                return JsonResult.error(400,res);
            case 401://:代表未授权
                return JsonResult.error(401,res);
            case 403://:代表禁止访问
                return JsonResult.error(403,res);
            case 404://:代表文件未找到\
                return JsonResult.error(404,res);
            case 500://:代表服务器错误
                return JsonResult.error(500,res);
            default://其他
                return JsonResult.error(statusCode,res);
        }
    }

}

 返回工具类

public class JsonResult<T> {
	private boolean success;
	private int errCode;
	private String errMsg = "";
	private T data;
	private List<T> list;

    //set get...
    //记得写默认的构造方法


    //ok构造参数
    public static <T> JsonResult<T> ok(T result) {
        return new JsonResult<T>(result);
    }

	public JsonResult(T result) {
		this.success=true;
        this.errCode = 0;
        this.errMsg = "OK";
        this.data = result;
    }

    //error
    public static <T> JsonResult<T> error(int code ,String result) {
		return new JsonResult<T>( code , result);
	}
	public JsonResult(int code ,String result) {
		this.success=false;
		this.errCode = code;
		this.errMsg = result;
	}
    
}

使用代码

//参数赋值
String url="http://.....";
Map<String, Object> map = new HashMap<>();



//使用
HttpClientUtil.HttpRequest("get", url, map);

猜你喜欢

转载自blog.csdn.net/qq_16513911/article/details/82856365