栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

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



public final class HttpUtilsTookit {

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

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

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

			HttpGet httpGet = new HttpGet(serverUrl);
			Iterator> header = headers.entrySet().iterator();
			while (header.hasNext()) {
				Entry 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 headers) {
		org.apache.http.client.HttpClient httpClient = null;
		String result = null;
		try {
			httpClient = createDefault();

			HttpPut httpPut = new HttpPut(serverUrl);
			Iterator> header = headers.entrySet().iterator();
			while (header.hasNext()) {
				Entry 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 headers) {
		org.apache.http.client.HttpClient httpClient = null;
		String result = null;
		try {
			httpClient = createDefault();

			HttpDelete httpPut = new HttpDelete(serverUrl);
			Iterator> header = headers.entrySet().iterator();
			while (header.hasNext()) {
				Entry 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 params) {
		String response = null;
		HttpClient client = new HttpClient();
		PostMethod method = new PostMethod(url);
		Iterator> iter = params.entrySet().iterator();
		while (iter.hasNext()) {
			Entry entry = (Entry) 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 headers) {
        org.apache.http.client.HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try {
            httpClient = new DefaultHttpClient();
            httpPost = new HttpPost(serverUrl);
            
            Iterator> header = headers.entrySet().iterator();
    		while (header.hasNext()) {
    			Entry 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;
	}

	
	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;
	}
	
	
	private static String buildSoapRequestData(String methodName, String namespace, Map paramMap) {
		StringBuffer soapRequestData = new StringBuffer();
		soapRequestData.append("");
		soapRequestData.append("");
		soapRequestData.append("<");
		soapRequestData.append(methodName);
		soapRequestData.append(" xmlns="");
		soapRequestData.append(namespace);
		soapRequestData.append("">");
		Set nameSet = paramMap.keySet();
		for (String name : nameSet) {
			soapRequestData.append("<");
			soapRequestData.append(name);
			soapRequestData.append(">");
			soapRequestData.append(paramMap.get(name));
			soapRequestData.append("");
		}
		soapRequestData.append("");
		soapRequestData.append("");
		soapRequestData.append("");
		return soapRequestData.toString();

	}

	
	public static String doSoap(String methodName, String namespace, TreeMap 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;
	}
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/532013.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号