Skip to content

NetWorkUtil #1

@maskleo

Description

@maskleo
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

public class NetWorkUtil {

	private static final Logger logger = LogManager.getLogger(NetWorkUtil.class);

	private static final String HTTP_HEAD = "http://";

	private static final String HTTPS_HEAD = "https://";

	public static final String CHARSET_UTF_8 = "UTF-8";

	public static String httpPost(String url, String charset, Map<String, String> params) throws IOException {
		CloseableHttpClient client = HttpClients.createDefault();
		return post(url, charset, params, client, -1, -1);
	}

	/**
	 * 设置请求超时时间
	 * 
	 * @param url
	 * @param charset
	 * @param params
	 * @param connectionTimeout
	 *            设置连接超时时间
	 * @param soTimeout
	 *            设置读数据超时时间
	 * @return
	 * @throws IOException
	 */
	public static String httpPost(String url, String charset, Map<String, String> params, int connectionTimeout, int soTimeout) throws IOException {
		CloseableHttpClient client = HttpClients.createDefault();
		return post(url, charset, params, client, connectionTimeout, soTimeout);
	}

	/**
	 * 
	 * @param url
	 * @param charset
	 * @param params
	 * @param client
	 * @param connectionTimeout
	 *            设置连接超时时间
	 * @param soTimeout
	 *            设置读数据超时时间
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	private static String post(String url, String charset, Map<String, String> params, CloseableHttpClient client, int connectionTimeout, int soTimeout) throws UnsupportedEncodingException, IOException, ClientProtocolException {

		String rst = "";
		HttpPost post = new HttpPost(url);
		if (soTimeout > -1) {
			// 设置读数据超时时间(单位毫秒)
			// client.getParams().setIntParameter("http.socket.timeout",soTimeout);
			post.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout);
		}
		if (connectionTimeout > -1) {
			// 设置连接超时时间(单位毫秒)
			post.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout);
		}

		List<NameValuePair> nvs = new ArrayList<NameValuePair>();
		if (params != null && !params.isEmpty()) {
			Set<String> keys = params.keySet();
			Iterator<String> itr = keys.iterator();
			while (itr.hasNext()) {
				String key = itr.next();
				String value = params.get(key);
				nvs.add(new BasicNameValuePair(key, value));
			}
		}
		UrlEncodedFormEntity entity = null;
		CloseableHttpResponse response = null;
		entity = new UrlEncodedFormEntity(nvs, charset);
		post.setEntity(entity);
		response = client.execute(post);
		rst = EntityUtils.toString(response.getEntity());
		response.close();
		client.close();
		return rst;
	}

	public static String httpsPost(String url, String charset, Map<String, String> params) throws Exception {
		CloseableHttpClient client = new SSLClient();
		return post(url, charset, params, client, -1, -1);
	}

	public static String post(String url, String charset, Map<String, String> params) throws Exception {
		return post(url, charset, params, -1, -1);
	}

	public static String post(String url, String charset, Map<String, String> params, int connectionTimeout, int soTimeout) throws Exception {
		CloseableHttpClient client = null;
		if (url.startsWith(HTTP_HEAD)) {
			client = HttpClients.createDefault();
		} else if (url.startsWith(HTTPS_HEAD)) {
			client = new SSLClient();
		} else {
			throw new MalformedURLException(MessageFormat.format("malformed url:{0},must start with {1} or {2}", new Object[] { url, HTTP_HEAD, HTTPS_HEAD }));
		}
		return post(url, charset, params, client, connectionTimeout, soTimeout);
	}

	public static final class HttpClientResult {

		private int statusCode;

		private String result;

		public HttpClientResult(int statusCode, String result) {
			super();
			this.statusCode = statusCode;
			this.result = result;
		}

		public HttpClientResult() {
			super();
		}

		public int getStatusCode() {
			return statusCode;
		}

		public void setStatusCode(int statusCode) {
			this.statusCode = statusCode;
		}

		public String getResult() {
			return result;
		}

		public void setResult(String result) {
			this.result = result;
		}

		@Override
		public String toString() {
			return "HttpClientResult [statusCode=" + statusCode + ", result=" + result + "]";
		}

	}

	public static HttpClientResult fullHttpPost(String url, String charset, Map<String, String> params) throws IOException {
		CloseableHttpClient client = HttpClients.createDefault();
		return fullPost(url, charset, params, client, -1, -1);
	}

	/**
	 * 设置请求超时时间
	 * 
	 * @param url
	 * @param charset
	 * @param params
	 * @param connectionTimeout
	 *            设置连接超时时间
	 * @param soTimeout
	 *            设置读数据超时时间
	 * @return
	 * @throws IOException
	 */
	public static HttpClientResult fullHttpPost(String url, String charset, Map<String, String> params, int connectionTimeout, int soTimeout) throws IOException {
		CloseableHttpClient client = HttpClients.createDefault();
		return fullPost(url, charset, params, client, connectionTimeout, soTimeout);
	}

	/**
	 * 
	 * @param url
	 * @param charset
	 * @param params
	 * @param client
	 * @param connectionTimeout
	 *            设置连接超时时间
	 * @param soTimeout
	 *            设置读数据超时时间
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	private static HttpClientResult fullPost(String url, String charset, Map<String, String> params, CloseableHttpClient client, int connectionTimeout, int soTimeout) throws UnsupportedEncodingException, IOException, ClientProtocolException {
		HttpClientResult result = new HttpClientResult();
		String rst;
		UrlEncodedFormEntity entity = null;
		CloseableHttpResponse response = null;
		try {
			rst = "";
			HttpPost post = new HttpPost(url);
			if (soTimeout > -1) {
				// 设置读数据超时时间(单位毫秒)
				// client.getParams().setIntParameter("http.socket.timeout",soTimeout);
				post.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout);
			}
			if (connectionTimeout > -1) {
				// 设置连接超时时间(单位毫秒)
				post.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout);
			}

			List<NameValuePair> nvs = new ArrayList<NameValuePair>();
			if (params != null && !params.isEmpty()) {
				Set<String> keys = params.keySet();
				Iterator<String> itr = keys.iterator();
				while (itr.hasNext()) {
					String key = itr.next();
					String value = params.get(key);
					nvs.add(new BasicNameValuePair(key, value));
				}
			}

			entity = new UrlEncodedFormEntity(nvs, charset);
			post.setEntity(entity);
			response = client.execute(post);
			int code = response.getStatusLine().getStatusCode();
			result.setStatusCode(code);
			rst = EntityUtils.toString(response.getEntity());
			result.setResult(rst);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("HttpClientResult:", e);
		} finally {
			logger.error(MessageFormat.format("url:{0},result:{1}", new Object[] { url, result.toString() }));
			if(response != null){
				response.close();
			}
			if(client != null){
				client.close();
			}
		}
		return result;
	}

	public static HttpClientResult fullHttpsPost(String url, String charset, Map<String, String> params) throws Exception {
		CloseableHttpClient client = new SSLClient();
		return fullPost(url, charset, params, client, -1, -1);
	}

	public static HttpClientResult fullPost(String url, String charset, Map<String, String> params) throws Exception {
		return fullPost(url, charset, params, -1, -1);
	}

	public static HttpClientResult fullPost(String url, String charset, Map<String, String> params, int connectionTimeout, int soTimeout) throws Exception {
		CloseableHttpClient client = null;
		if (url.startsWith(HTTP_HEAD)) {
			client = HttpClients.createDefault();
		} else if (url.startsWith(HTTPS_HEAD)) {
			client = new SSLClient();
		} else {
			throw new MalformedURLException(MessageFormat.format("malformed url:{0},must start with {1} or {2}", new Object[] { url, HTTP_HEAD, HTTPS_HEAD }));
		}
		return fullPost(url, charset, params, client, connectionTimeout, soTimeout);
	}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions