GET、POST请求工具类

HttpRequestUtil工具类

import io.micrometer.core.instrument.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class HttpRequestUtil {

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

    /**
     * get请求
     *
     * @param url
     * @return
     * @throws IOException
     */
    public static String sendGet(String url) throws IOException {
        return sendGet(url, null);
    }

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url   发送请求的URL
     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) throws IOException {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url;
            if (StringUtils.isNotBlank(param)) {
                urlNameString += "?" + param;
            }
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param, String token) throws IOException {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            if (token != null && !"".equals(token)) {
                conn.setRequestProperty("token", token);
            }
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            logger.error("发送 POST 请求出现异常!", e);
            throw e;
        } finally {
            //使用finally块来关闭输出流、输入流
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) throws IOException {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            logger.error("发送 POST 请求出现异常!", e);
            throw e;
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url 发送请求的 URL
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url) throws IOException {
        return sendPost(url, "");
    }

    /**
     * @param requestUrl    请求地址
     * @param requestMethod 请求方法
     * @param outputStr     参数
     */
    public static String httpRequest(String requestUrl, String requestMethod, String outputStr) {        // 创建SSLContext
        StringBuffer buffer = null;
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod(requestMethod);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.connect();
            // 往服务器端写内容
            if (null != outputStr) {
                OutputStream os = conn.getOutputStream();
                os.write(outputStr.getBytes("utf-8"));
                os.close();
            }
            // 读取服务器端返回的内容
            InputStream is = conn.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, "utf-8");
            BufferedReader br = new BufferedReader(isr);
            buffer = new StringBuffer();
            String line = null;
            while ((line = br.readLine()) != null) {
                buffer.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }
}

详细版

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author sunny
 *
 */
public class HttpUtil {

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

	public static String get(String url, Map<String, String> headerMap) throws IOException {
		HttpClient client = HttpClientBuilder.create().build();
		HttpGet request = new HttpGet(url);
		if (null != headerMap) {
			headerHandle(headerMap, false);
			headerMap.forEach(request::addHeader);
		}
		HttpResponse response = client.execute(request);
		String responseBody = responseHandle(response);
		request.releaseConnection();
		return responseBody;
	}

	public static String delete(String url, Map<String, String> headerMap) throws IOException {
		HttpClient client = HttpClientBuilder.create().build();
		HttpDelete request = new HttpDelete(url);
		if (null != headerMap) {
			headerHandle(headerMap, false);
			headerMap.forEach(request::addHeader);
		}
		HttpResponse response = client.execute(request);
		String responseBody = responseHandle(response);
		request.releaseConnection();
		return responseBody;
	}

	public static String put(String url, Map<String, String> headerMap, Object requestBody) throws IOException {
		HttpClient httpClient = HttpClientBuilder.create().build();
		HttpPut request = new HttpPut(url);
		headerHandle(headerMap, true);
		headerMap.forEach(request::addHeader);
		request.setEntity(requestBodyHandle(requestBody));
		HttpResponse response = httpClient.execute(request);
		String responseBody = responseHandle(response);
		request.releaseConnection();
		return responseBody;
	}


	public static String post(String url, Object requestBody) throws IOException {
		return post(url,new HashMap<>(),requestBody);
	}

	public static String post(String url, Map<String, String> headerMap, Object requestBody) throws IOException {
		HttpClient httpClient = HttpClientBuilder.create().build();
		HttpPost request = new HttpPost(url);
		headerHandle(headerMap, true);
		headerMap.forEach(request::addHeader);
		request.setEntity(requestBodyHandle(requestBody));
		logger.info("请求参数: {}", JSONObject.toJSONString(requestBody));
		logger.info("请求头:{}", request.getAllHeaders());
		logger.info("requestUrl :{}", url);

		HttpResponse response = httpClient.execute(request);
		logger.info("HttpResponse : {}", JSONObject.toJSONString(response));
		String responseBody = responseHandle(response);
		request.releaseConnection();
		return responseBody;
	}


	public static String patch(String url, Map<String, String> headerMap, Object requestBody) throws IOException {
		HttpClient httpClient = HttpClientBuilder.create().build();
		HttpPatch request = new HttpPatch(url);
		headerHandle(headerMap, true);
		headerMap.forEach(request::addHeader);
		request.setEntity(requestBodyHandle(requestBody));
		HttpResponse response = httpClient.execute(request);
		String responseBody = responseHandle(response);
		request.releaseConnection();
		return responseBody;
	}
	
	public static String get(String url) throws IOException{
		return get(url, null);
	}

	private static void headerHandle(Map<String, String> headerMap, boolean contentType) {
		if (null == headerMap) {
			headerMap = new HashMap<>();
		}
		if (contentType) {
			headerMap.put("Content-type", "application/json");
		}
	}

	// 参数转string
	private static StringEntity requestBodyHandle(Object requestBody) {
		String paramsStr = JsonUtil.toJsonString(requestBody);
		return requestBody == null ? null : new StringEntity(paramsStr, "UTF-8");
	}

	public static String responseHandle(HttpResponse response) throws IOException {
		ResponseHandler<String> handler = new BasicResponseHandler();
		StatusLine statusLine = response.getStatusLine();
		int responseCode = statusLine.getStatusCode();
		String responseBody;
		if (responseCode == 200) {
			responseBody = handler.handleResponse(response);
		} else if (responseCode == 403) {
			responseBody = handler.handleResponse(response);
		} else if (responseCode == 204) {
			responseBody = null;
		} else {
			throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
		}
		return responseBody;
	}

	/**
	 * 从HttpServletRequest中获取body中的数据  避免对象转jsonStr参数顺序错乱导致验签失败
	 * @param request
	 * @return
	 */
	public static String readAsChars(HttpServletRequest request) {

		BufferedReader br = null;
		StringBuilder sb = new StringBuilder("");
		try {
			br = request.getReader();
			String str;
			while ((str = br.readLine()) != null)
			{
				sb.append(str);
			}
			br.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != br) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return sb.toString();
	}


	/**
	 * httppost请求
	 * @param url
	 * @param urlParam
	 * @param headerMap
	 * @param body
	 * @return
	 */
	public static String doPost (String url, Map<String, String> urlParam, Map<String, String> headerMap, String body) {

		CloseableHttpResponse response = null;
		try {
			RequestConfig defaultRequestConfig = RequestConfig.custom()
					.setSocketTimeout(6000)
					.setConnectTimeout(6000)
					.setConnectionRequestTimeout(6000)
					.build();
			CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
//            HttpPost httpPost = new HttpPost(POST_URL);
			StringBuilder param=new StringBuilder("");
            //将要拼接的参数urlencode
			if (null != urlParam){
				for (String key:urlParam.keySet()){
					param.append(key + "=" + URLEncoder.encode(urlParam.get(key), "UTF-8") + "&");
				}
			}
           //pingjie
			HttpPost httpPost = new HttpPost(url+param.toString());
            //请求参数设置
			if(StringUtil.isNotEmpty(body)){
				StringEntity entity=new StringEntity(body, ContentType.APPLICATION_JSON);
				httpPost.setEntity(entity);
			}
			//请求头
			if (null != headerMap){
				for (Map.Entry<String, String> entry : headerMap.entrySet()) {
					httpPost.addHeader(entry.getKey(), entry.getValue());
				}

			}
			response = httpclient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			return EntityUtils.toString(entity, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			logger.error(e.getMessage(), e);
		} catch (ClientProtocolException e) {
			logger.error(e.getMessage(), e);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		} catch (Exception e){
			System.out.println(e);
		}finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					logger.error(e.getMessage(), e);
				}
			}

		}

		return null;

	}

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值