JFinal中httpKit超时时间

发布于 2021-11-30 04:30:47 字数 186 浏览 501 评论 4

@JFinal 一直有个疑问,在用1.9版本的时候遇到过需要自定义超时时间的问题,就重写了工具类解决。我记得波总说过2.0后会考虑增加这个功能,我在2.2中似乎也没看到嘛。还要重写这个工具类?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

悸初 2021-12-01 18:19:12

好哒,谢谢

哑剧 2021-12-01 17:51:34

我试试,谢谢啦

终陌 2021-12-01 16:25:40

源码:https://github.com/JpressProjects/jpress/blob/master/jpress/src/io/jpress/utils/HttpUtils.java

/**
 * Copyright (c) 2015-2016, Michael Yang 杨福海 (fuhai999@gmail.com).
 *
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.gnu.org/licenses/lgpl-3.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.jpress.utils;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class HttpUtils {

	private static final String TAG = "HttpHandler";
	private static final int mReadTimeOut = 1000 * 10; // 10秒
	private static final int mConnectTimeOut = 1000 * 5; // 5秒
	private static final String CHAR_SET = "utf-8";
	private static final int mRetry = 2; // 默认尝试访问次数

	public static String get(String url) throws Exception {
		return get(url, null);
	}

	public static String get(String url, Map<String, ? extends Object> params) throws Exception {
		return get(url, params, null);
	}

	public static String get(String url, Map<String, ? extends Object> params, Map<String, String> headers)
			throws Exception {
		if (url == null || url.trim().length() == 0) {
			throw new Exception(TAG + ": get url is null or empty!");
		}

		if (params != null && params.size() > 0) {
			if (!url.contains("?"))
				url += "?";

			StringBuilder sbContent = new StringBuilder();
			if (url.charAt(url.length() - 1) == '?') { // 最后一个字符是 ?
				for (Map.Entry<String, ? extends Object> entry : params.entrySet()) {
					if (entry.getKey() != null)
						sbContent.append(entry.getKey().trim()).append("=").append(entry.getValue()).append("&");
				}

				if (sbContent.charAt(sbContent.length() - 1) == '&') {
					sbContent.deleteCharAt(sbContent.length() - 1);
				}
			} else {
				for (Map.Entry<String, ? extends Object> entry : params.entrySet()) {
					if (entry.getKey() != null)
						sbContent.append("&").append(entry.getKey().trim()).append("=").append(entry.getValue());
				}
			}
			url += sbContent.toString();
		}

		return tryToGet(url, headers);
	}

	private static String tryToGet(String url, Map<String, String> headers) throws Exception {
		int tryTime = 0;
		Exception ex = null;
		while (tryTime < mRetry) {
			try {
				return doGet(url, headers);
			} catch (Exception e) {
				if (e != null)
					ex = e;
				tryTime++;
			}
		}
		if (ex != null)
			throw ex;
		else
			throw new Exception("未知网络错误 ");
	}

	private static String doGet(String strUrl, Map<String, String> headers) throws Exception {
		strUrl = urlEncode(strUrl, CHAR_SET);
		HttpURLConnection connection = null;
		InputStream stream = null;
		try {

			connection = getConnection(strUrl);
			configConnection(connection);
			if (headers != null && headers.size() > 0) {
				for (Map.Entry<String, String> entry : headers.entrySet()) {
					connection.setRequestProperty(entry.getKey(), entry.getValue());
				}
			}

			connection.setInstanceFollowRedirects(true);
			connection.connect();

			stream = connection.getInputStream();
			ByteArrayOutputStream obs = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			for (int len = 0; (len = stream.read(buffer)) > 0;) {
				obs.write(buffer, 0, len);
			}
			obs.flush();
			obs.close();
			stream.close();

			return new String(obs.toByteArray());
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
			if (stream != null) {
				stream.close();
			}
		}
	}

	public static String post(String url) throws Exception {
		return post(url, null);
	}

	public static String post(String url, Map<String, ? extends Object> params) throws Exception {
		return post(url, params, null);
	}

	public static String post(String url, Map<String, ? extends Object> params, Map<String, String> headers)
			throws Exception {
		if (url == null || url.trim().length() == 0) {
			throw new Exception(TAG + ": post url is null or empty!");
		}

		if (params != null && params.size() > 0) {
			StringBuilder sbContent = new StringBuilder();
			for (Map.Entry<String, ? extends Object> entry : params.entrySet()) {
				if (entry.getKey() != null)
					sbContent.append("&").append(entry.getKey().trim()).append("=").append(entry.getValue());
			}
			return tryToPost(url, sbContent.substring(1), headers);

		} else {
			return tryToPost(url, null, headers);
		}
	}

	public static String post(String url, String content, Map<String, String> headers) throws Exception {
		return tryToPost(url, content, headers);
	}

	private static String tryToPost(String url, String postContent, Map<String, String> headers) throws Exception {
		int tryTime = 0;
		Exception ex = null;
		while (tryTime < mRetry) {
			try {
				return doPost(url, postContent, headers);
			} catch (Exception e) {
				if (e != null)
					ex = e;
				tryTime++;
			}
		}
		if (ex != null)
			throw ex;
		else
			throw new Exception("未知网络错误 ");
	}

	private static String doPost(String strUrl, String postContent, Map<String, String> headers) throws Exception {
		HttpURLConnection connection = null;
		InputStream stream = null;
		try {
			connection = getConnection(strUrl);
			configConnection(connection);
			if (headers != null && headers.size() > 0) {
				for (Map.Entry<String, String> entry : headers.entrySet()) {
					connection.setRequestProperty(entry.getKey(), entry.getValue());
				}
			}

			connection.setRequestMethod("POST");
			connection.setDoOutput(true);

			if (null != postContent && !"".equals(postContent)) {
				DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
				dos.write(postContent.getBytes(CHAR_SET));
				dos.flush();
				dos.close();
			}
			stream = connection.getInputStream();
			ByteArrayOutputStream obs = new ByteArrayOutputStream();

			byte[] buffer = new byte[1024];
			for (int len = 0; (len = stream.read(buffer)) > 0;) {
				obs.write(buffer, 0, len);
			}
			obs.flush();
			obs.close();

			return new String(obs.toByteArray());

		} finally {
			if (connection != null) {
				connection.disconnect();
			}
			if (stream != null) {
				stream.close();
			}
		}

	}

	private static void configConnection(HttpURLConnection connection) {
		if (connection == null)
			return;
		connection.setReadTimeout(mReadTimeOut);
		connection.setConnectTimeout(mConnectTimeOut);

		connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		connection.setRequestProperty("User-Agent",
				"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
	}

	private static HttpURLConnection getConnection(String strUrl) throws Exception {
		if (strUrl == null) {
			return null;
		}
		if (strUrl.toLowerCase().startsWith("https")) {
			try {
				return getHttpsConnection(strUrl);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		} else {
			return getHttpConnection(strUrl);
		}
	}

	private static HttpURLConnection getHttpConnection(String urlStr) throws Exception {
		URL url = new URL(urlStr);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		return conn;
	}

	private static HttpsURLConnection getHttpsConnection(String urlStr) throws Exception {
		URL url = new URL(urlStr);
		HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
		conn.setHostnameVerifier(hnv);
		SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
		if (sslContext != null) {
			TrustManager[] tm = { xtm };
			sslContext.init(null, tm, null);
			SSLSocketFactory ssf = sslContext.getSocketFactory();
			conn.setSSLSocketFactory(ssf);
		}

		return conn;
	}

	private static X509TrustManager xtm = new X509TrustManager() {
		public void checkClientTrusted(X509Certificate[] chain, String authType) {
		}

		public void checkServerTrusted(X509Certificate[] chain, String authType) {
		}

		public X509Certificate[] getAcceptedIssuers() {
			return null;
		}
	};

	private static HostnameVerifier hnv = new HostnameVerifier() {
		public boolean verify(String hostname, SSLSession session) {
			return true;
		}
	};

	public static String urlEncode(String str, String charset) throws UnsupportedEncodingException {
		Pattern pattern = Pattern.compile("[u4e00-u9fa5]+");
		Matcher mathcer = pattern.matcher(str);
		StringBuffer buffer = new StringBuffer();
		while (mathcer.find()) {
			mathcer.appendReplacement(buffer, URLEncoder.encode(mathcer.group(0), charset));
		}
		mathcer.appendTail(buffer);
		return buffer.toString();
	}

}

超时重试3次,不谢。

多彩岁月 2021-12-01 15:43:55

    2.2 版本没顾上这个功能,要知道 jfinal 每次升级波总都会选择在一个比较大的时间片段去写程序,例如五一、国庆、元旦之类的,这些比较长的时间段需要集中精力做最重要的功能,会有一些小功能往后放

    平时回复大家的问答都在不断收集和备忘一些反馈,以便在下版本中做出改进。

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文