Java HttpUtilsTookit-请求调用第三方接口工具类

Java HttpUtilsTookit-请求调用第三方接口工具类

直接复制过去,创建一个Util工具类


/**
 *  @Description:  请求调用第三方接口工具类
 *  @Author LeMenPan
 *  @Date 2021/11/17
 *  @Version 0.0.1
 */

public final class HttpUtilsTookit {

	private static Log log = LogFactory.getLog(HttpUtilsTookit.class);

	/**
	 * CloseableHttpClient
	 * @return
	 */
	public static CloseableHttpClient createDefault() {
		return HttpClientBuilder.create().build();
	}

	public static String doGet(String serverUrl, Map<String, String> headers) {
		org.apache.http.client.HttpClient httpClient = null;
		String result = null;
		try {
			httpClient = createDefault();

			HttpGet httpGet = new HttpGet(serverUrl);
			Iterator<Entry<String, String>> header = headers.entrySet().iterator();
			while (header.hasNext()) {
				Entry<String, String> entry = header.next();
				httpGet.addHeader(entry.getKey(), entry.getValue());
			}

			HttpResponse response = httpClient.execute(httpGet);
			if (response != null) {
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = EntityUtils.toString(resEntity);
				}
			}
		} catch (Exception ex) {
			log.error("doGet Exception ", ex);
		}
		return result;
	}

	public static String doPut(String serverUrl, Map<String, String> headers) {
		org.apache.http.client.HttpClient httpClient = null;
		String result = null;
		try {
			httpClient = createDefault();

			HttpPut httpPut = new HttpPut(serverUrl);
			Iterator<Entry<String, String>> header = headers.entrySet().iterator();
			while (header.hasNext()) {
				Entry<String, String> entry = header.next();
				httpPut.addHeader(entry.getKey(), entry.getValue());
			}

			HttpResponse response = httpClient.execute(httpPut);
			if (response != null) {
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = EntityUtils.toString(resEntity);
				}
			}
		} catch (Exception ex) {
			log.error("doGet Exception ", ex);
		}
		return result;
	}

	public static String doDelete(String serverUrl, Map<String, String> headers) {
		org.apache.http.client.HttpClient httpClient = null;
		String result = null;
		try {
			httpClient = createDefault();

			HttpDelete httpPut = new HttpDelete(serverUrl);
			Iterator<Entry<String, String>> header = headers.entrySet().iterator();
			while (header.hasNext()) {
				Entry<String, String> entry = header.next();
				httpPut.addHeader(entry.getKey(), entry.getValue());
			}

			HttpResponse response = httpClient.execute(httpPut);
			if (response != null) {
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = EntityUtils.toString(resEntity);
				}
			}
		} catch (Exception ex) {
			log.error("doGet Exception ", ex);
		}
		return result;
	}

	public static String doGet(String url, String queryString) {
		String response = null;
		HttpClient client = new HttpClient();
		HttpMethod method = new GetMethod(url);
		try {
			if (StringUtils.isNotBlank(queryString))
				method.setQueryString(URIUtil.encodeQuery(queryString));
			client.executeMethod(method);
			if (method.getStatusCode() == 200)
				response = method.getResponseBodyAsString();
		} catch (URIException e) {
			log.error("执行HTTP Get请求时,编码查询字符串“" + queryString + "”发生异常!", e);
		} catch (IOException e) {
			log.error("执行HTTP Get请求" + url + "时,发生异常!", e);
		} finally {
			method.releaseConnection();
		}
		return response;
	}

	public static String doPost(String url, Map<String, String> params) {
		String response = null;
		HttpClient client = new HttpClient();
		PostMethod method = new PostMethod(url);
		Iterator<Entry<String, String>> iter = params.entrySet().iterator();
		while (iter.hasNext()) {
			Entry<String, String> entry = (Entry<String, String>) iter
					.next();
			method.addParameter(entry.getKey(), entry.getValue());
		}
		method.addRequestHeader("Content-Type",
				"application/x-www-form-urlencoded;charset=UTF-8");

		try {
			client.executeMethod(method);
			System.out.println(method.getStatusCode());
			if (method.getStatusCode() == 200) {
				response = method.getResponseBodyAsString();
			}else {
				response = "http post error "+method.getStatusCode();
			}
		} catch (IOException e) {
			log.error("执行HTTP Post请求" + url + "时,发生异常!", e);
			response = e.getMessage();
		} finally {
			method.releaseConnection();
		}

		return response;
	}
	
	public static String doPost(String serverUrl, String params, Map<String, String> headers) {
        org.apache.http.client.HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try {
            httpClient = new DefaultHttpClient();
            httpPost = new HttpPost(serverUrl);
            
            Iterator<Entry<String, String>> header = headers.entrySet().iterator();
    		while (header.hasNext()) {
    			Entry<String, String> entry = header.next();
    			httpPost.addHeader(entry.getKey(), entry.getValue()); 
    		}
            
            StringEntity stringEntity = new StringEntity(params, StandardCharsets.UTF_8);
            httpPost.setEntity(stringEntity);
            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                	result = EntityUtils.toString(resEntity);
                }
            }
        } catch (Exception ex) {
			log.error("doPost Exception ", ex);
            result = ex.getMessage();

        }
        return result;
    }  

	public static String sendGet(String url) {
		String msg = "";
		try {
			HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(
					url).openConnection();
			msg = creatConnection(url, httpURLConnection);
		} catch (IOException io) {
			log.error("http close" + io);
		}
		return msg;
	}

	private static String creatConnection(String url,
			HttpURLConnection httpURLConnection) {
		String msg = "";
		try {
			if (httpURLConnection != null) {
				httpURLConnection.disconnect();
			}
			httpURLConnection = (HttpURLConnection) new URL(url)
					.openConnection();
			httpURLConnection.setRequestMethod("GET");
			httpURLConnection.setRequestProperty("Content-Type",
					"text/html;charset=utf-8");
			msg = receiveMessage(httpURLConnection);
		} catch (IOException io) {
			io.printStackTrace();
			log.error("Http Connect to :" + url + " " + "IOFail!");
		} catch (Exception ex) {
			log.error("Http Connect to :" + url + " " + "Failed" + ex);
		} finally {
			closeConnection(httpURLConnection);
		}
		return msg;
	}

	private static void closeConnection(HttpURLConnection httpURLConnection) {
		try {
			if (httpURLConnection != null)
				httpURLConnection.disconnect();
		} catch (Exception localException) {
		}
	}

	private static String receiveMessage(HttpURLConnection httpURLConnection) {
		String responseBody = null;
		try {
			InputStream httpIn = httpURLConnection.getInputStream();
			if (httpIn != null) {
				ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
				byte tempByte;
				while (-1 != (tempByte = (byte) httpIn.read())) {
					byte tempByte1 = 0;
					byteOut.write(tempByte1);
				}
				responseBody = new String(byteOut.toByteArray(), "utf-8");
			}
		} catch (IOException ioe) {
			log.error("Http Connect tosss :" + ioe.getLocalizedMessage() + " "
					+ "IOEFail!");
			return null;
		}
		return responseBody;
	}

	/**
	 * 获取真实IP
	 * 
	 * @param request
	 * @return
	 */
	public static String getRealIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("X-Real-IP");
		if ((ip == null) || (ip.length() == 0)
				|| ("unknown".equalsIgnoreCase(ip))) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if ((ip == null) || (ip.length() == 0)
				|| ("unknown".equalsIgnoreCase(ip))) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if ((ip == null) || (ip.length() == 0)
				|| ("unknown".equalsIgnoreCase(ip))) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	public static String getPath(HttpServletRequest request) {
		String path = request.getContextPath();
		return request.getScheme() + "://" + request.getServerName() + ":"
				+ request.getServerPort() + path + "/";
	}
	
	public static String getDomain(HttpServletRequest request) {
		StringBuffer url = request.getRequestURL();
		String domain = url.delete(url.length() - request.getRequestURI().length(), url.length())
				.append(request.getContextPath()).toString();
		return domain;
	}
	
	/**
	 * 构建soap参数
	 * @param methodName 调用webservice的方法名
	 * @param namespace webservice命名空间
	 * @param paramMap 提交的参数
	 * @return
	 */
	private static String buildSoapRequestData(String methodName, String namespace, Map<String, String> paramMap) {
		StringBuffer soapRequestData = new StringBuffer();
		soapRequestData.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
		soapRequestData.append("<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">");
		soapRequestData.append("<soap12:Body><");
		soapRequestData.append(methodName);
		soapRequestData.append(" xmlns=\"");
		soapRequestData.append(namespace);
		soapRequestData.append("\">");
		Set<String> nameSet = paramMap.keySet();
		for (String name : nameSet) {
			soapRequestData.append("<");
			soapRequestData.append(name);
			soapRequestData.append(">");
			soapRequestData.append(paramMap.get(name));
			soapRequestData.append("</");
			soapRequestData.append(name);
			soapRequestData.append(">");
		}
		soapRequestData.append("</");
		soapRequestData.append(methodName);
		soapRequestData.append(">");
		soapRequestData.append("</soap12:Body>");
		soapRequestData.append("</soap12:Envelope>");
		return soapRequestData.toString();

	}

	/**
	 * httpclient提交soap
	 * @param methodName 调用webservice的方法名
	 * @param namespace webservice命名空间
	 * @param paramMap 提交的参数
	 * @param wsdlLocation 提交地址
	 * @return
	 */
	public static String doSoap(String methodName, String namespace, TreeMap<String, String> paramMap,
			String wsdlLocation) {
		PostMethod postMethod = new PostMethod(wsdlLocation);
		String soapRequestData = buildSoapRequestData(methodName, namespace, paramMap);
		try {
			byte[] bytes = soapRequestData.getBytes("utf-8");
			InputStream inputStream = new ByteArrayInputStream(bytes, 0, bytes.length);
			RequestEntity requestEntity = new InputStreamRequestEntity(inputStream, bytes.length, "application/soap+xml; charset=utf-8");
			postMethod.setRequestEntity(requestEntity);

			HttpClient httpClient = new HttpClient();
			System.out.println("postMethod="+postMethod);
			int r = httpClient.executeMethod(postMethod);
			System.out.println("r="+r);
			return postMethod.getResponseBodyAsString();
		} catch (UnsupportedEncodingException e) {
			System.out.println("执行HTTP doSoap请求" + wsdlLocation + "时,发生异常!"+ e);
		} catch (HttpException e) {
			System.out.println("执行HTTP doSoap请求" + wsdlLocation + "时,发生异常!"+ e);
		} catch (IOException e) {
			System.out.println("执行HTTP doSoap请求" + wsdlLocation + "时,发生异常!"+ e);
		} finally {
			postMethod.releaseConnection();
		}
		return null;
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值