请求工具类

package com.eebbk.content.ai.makequestion.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
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.util.EntityUtils;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@Slf4j
public class HttpRequestUtil {
	/**
	 * 功能描述:
	 * @param: json版的post请求
	 * @return:
	 * @auther: lipf
	 * @date: 2019/12/4 17:20
	 */
	public static String doJsonPost(String urlPath, String Json) {
		 //System.out.println("data="+Json);
	        String result = "";
	        BufferedReader reader = null;
	        try {
	            URL url = new URL(urlPath);
	            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	            conn.setRequestMethod("POST");
	            conn.setDoOutput(true);
	            conn.setUseCaches(false);
				conn.setConnectTimeout(6*60*1000);
				conn.setReadTimeout(6*60*1000);
	            conn.setRequestProperty("Connection", "Keep-Alive");
	            conn.setRequestProperty("Charset", "UTF-8");
	            // 设置文件类型:
	            conn.setRequestProperty("Content-Type","application/json; charset=UTF-8");
	            // 设置接收类型否则返回415错误
//	            conn.setRequestProperty("accept","*/*");//此处为暴力方法设置接受所有类型,以此来防范返回415;
	            conn.setRequestProperty("accept","application/json");
//	            conn.setRequestProperty("accept","application/x-www-form-urlencoded");
//	            conn.setRequestProperty("accept","multipart/form-data;charset=utf-8");
	            // 往服务器里面发送数据
	            conn.setDoInput(true);
	            if (Json != null &&!"".equals(Json)) {
	                byte[] writebytes = Json.getBytes();
	                // 设置文件长度
	                conn.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
	                conn.setDoOutput(true);
	                OutputStream outwritestream = conn.getOutputStream();
	                outwritestream.write(Json.getBytes());
	                outwritestream.flush();
	                outwritestream.close();
	            }
	            if (conn.getResponseCode() == 200) {
	                reader = new BufferedReader(
	                        new InputStreamReader(conn.getInputStream()));
	                result = reader.readLine();
					log.info("resultSucess="+result);
	            }else{
	            	reader = new BufferedReader(
	                        new InputStreamReader(conn.getInputStream()));
	                result = reader.readLine();
	                log.error("resultFailure="+result);
	            }
	        } catch (Exception e) {
				log.error("通过工具类掉接口失败:"+e.toString());
				e.printStackTrace();
	        } finally {
	            if (reader != null) {
	                try {
	                    reader.close();
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
	        }
	        return result;
	}
	/**
	 * 功能描述:
	 * @param: 携带请求头的
	 * @return:
	 * @auther: lipf
	 * @date: 2019/12/4 17:25
	 */
	public static String doJsonHeaderPost(String urlPath, HashMap header,String Json) {
		//log.info("data="+Json);
		String result = "";
		BufferedReader reader = null;
		try {
			URL url = new URL(urlPath);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			if (header!=null){
				for (String key : header.keySet()){
					if (header.get(key)!=null)
					  conn.setRequestProperty(key,header.get(key).toString());
				}
			}
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("Charset", "UTF-8");
			// 设置文件类型:
			conn.setRequestProperty("Content-Type","application/json; charset=UTF-8");
			// 设置接收类型否则返回415错误
	            conn.setRequestProperty("accept","*/*");//此处为暴力方法设置接受所有类型,以此来防范返回415;
			// 往服务器里面发送数据
			conn.setDoInput(true);
			if (Json != null &&!"".equals(Json)) {
				byte[] writebytes = Json.getBytes();
				// 设置文件长度
				conn.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
				conn.setDoOutput(true);
				OutputStream outwritestream = conn.getOutputStream();
				outwritestream.write(Json.getBytes());
				outwritestream.flush();
				outwritestream.close();
			}
			if (conn.getResponseCode() == 200) {
				reader = new BufferedReader(
						new InputStreamReader(conn.getInputStream()));
				result = reader.readLine();
				log.info("resultSucess="+result);
			}else{
				reader = new BufferedReader(
						new InputStreamReader(conn.getInputStream()));
				result = reader.readLine();
				log.error("resultFailure="+result);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}
	/**
	 * 带参数的get请求
	 * @param url
	 * @param param
	 * @return String
	 */
	public static String doGet(String url, Map param) {
		// 创建Httpclient对象
		CloseableHttpClient httpclient = HttpClients.createDefault();

		String resultString = "";
		CloseableHttpResponse response = null;
		try {
			// 创建uri
			URIBuilder builder = new URIBuilder(url);
			if (param != null) {
				for (String key : param.keySet()) {
					builder.addParameter(key, param.get(key));
				}
			}
			URI uri = builder.build();
			// 创建http GET请求
			HttpGet httpGet = new HttpGet(uri);
			// 执行请求
			response = httpclient.execute(httpGet);
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}
	

    /**
     * 功能描述: 
     * @param: map请求delete 
     * @return: 
     * @auther: lipf
     * @date: 2019/12/4 17:16
     */
	public static String doDelete(String urlPath,Map param) {
		String result = "";
		BufferedReader reader = null;
		try {
			URL url = new URL(urlPath);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("DELETE");
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("Charset", "UTF-8");
			// 设置文件类型:
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
			// 设置接收类型否则返回415错误
			conn.setRequestProperty("accept","*/*");//此处为暴力方法设置接受所有类型,以此来防范返回415;
			// 往服务器里面发送数据
			conn.setDoInput(true);
			StringBuffer requestParams = new StringBuffer();
			if (param!=null){
				Set strings = param.keySet();
				for (String key:param.keySet())
					requestParams.append(key).append("=").append(param.get(key)).append("&");
					String request = requestParams.substring(0, requestParams.length() - 1);
					conn.getOutputStream().write(request.getBytes());// 输入参数
			}
			if (conn.getResponseCode() == 200) {
				reader = new BufferedReader(
						new InputStreamReader(conn.getInputStream()));
				result = reader.readLine();
				System.out.println("resultSucess="+result);
			}else{
				reader = new BufferedReader(
						new InputStreamReader(conn.getInputStream()));
				result = reader.readLine();
				System.out.println("resultFailure="+result);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}

	public static String doDeleteOk(String url, Map param) {
		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			// 创建uri
			URIBuilder builder = new URIBuilder(url);
			if (param != null) {
				for (String key : param.keySet()) {
					builder.addParameter(key, param.get(key));
				}
			}
			URI uri = builder.build();
			// 创建Http Delete请求
			HttpDelete httpDelete = new HttpDelete(uri);
			// 执行http请求
			response = httpClient.execute(httpDelete);
			resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}
	/**
	 * 功能描述:
	 * @param: put类型的请求,表单模式
	 * @return:
	 * @auther: lipf
	 * @date: 2019/12/4 17:21
	 */
	public static String doPut(String urlPath,Map param) {
		String result = "";
		BufferedReader reader = null;
		try {
			URL url = new URL(urlPath);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("PUT");
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("Charset", "UTF-8");
			// 设置文件类型:
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
			// 设置接收类型否则返回415错误
			conn.setRequestProperty("accept","*/*");//此处为暴力方法设置接受所有类型,以此来防范返回415;
			// 往服务器里面发送数据
			conn.setDoInput(true);
			StringBuffer requestParams = new StringBuffer();
			if (param!=null){
				Set strings = param.keySet();
				for (String key:param.keySet())
					requestParams.append(key).append("=").append(param.get(key)).append("&");
				String request = requestParams.substring(0, requestParams.length() - 1);
				conn.getOutputStream().write(request.getBytes());// 输入参数
			}
			if (conn.getResponseCode() == 200) {
				reader = new BufferedReader(
						new InputStreamReader(conn.getInputStream()));
				result = reader.readLine();
				System.out.println("resultSucess="+result);
			}else{
				reader = new BufferedReader(
						new InputStreamReader(conn.getInputStream()));
				result = reader.readLine();
				System.out.println("resultFailure="+result);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}

	/**
	 * 功能描述:
	 * @param: Put请求json类型的请求
	 * @return:
	 * @auther: lipf
	 * @date: 2019/12/4 17:22
	 */
	public static String doPutJson(String urlPath,String json) {
		String result = "";
		BufferedReader reader = null;
		try {
			URL url = new URL(urlPath);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("PUT");
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("Charset", "UTF-8");
			// 设置文件类型:
			conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
			// 设置接收类型否则返回415错误
			conn.setRequestProperty("accept","*/*");//此处为暴力方法设置接受所有类型,以此来防范返回415;
			// 往服务器里面发送数据
			conn.setDoInput(true);
			StringBuffer requestParams = new StringBuffer();
			if (StringUtils.isEmpty(json)) {
				byte[] writebytes = json.getBytes();
				// 设置文件长度
				conn.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
				conn.setDoOutput(true);
				OutputStream outwritestream = conn.getOutputStream();
				outwritestream.write(json.getBytes());
				outwritestream.flush();
				outwritestream.close();
			}
			if (conn.getResponseCode() == 200) {
				reader = new BufferedReader(
						new InputStreamReader(conn.getInputStream()));
				result = reader.readLine();
				System.out.println("resultSucess="+result);
			}else{
				reader = new BufferedReader(
						new InputStreamReader(conn.getInputStream()));
				result = reader.readLine();
				System.out.println("resultFailure="+result);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}


}

 

你可能感兴趣的:(javaweb接口调用)